Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,800 | def on_name(self, node): # ('id', 'ctx')
""" Name node """
ctx = node.ctx.__class__
if ctx == ast.Del:
val = self.symtable.del_symbol(node.id)
elif ctx == ast.Param: # for Function Def
val = str(node.id)
else:
# val = self.symtable.get_symb... | NameError | dataset/ETHPy150Open xraypy/xraylarch/lib/interpreter.py/Interpreter.on_name |
2,801 | def on_attribute(self, node): # ('value', 'attr', 'ctx')
"extract attribute"
ctx = node.ctx.__class__
if ctx == ast.Del:
return delattr(sym, node.attr)
sym = self.run(node.value)
if node.attr not in UNSAFE_ATTRS:
try:
return getattr(sym... | AttributeError | dataset/ETHPy150Open xraypy/xraylarch/lib/interpreter.py/Interpreter.on_attribute |
2,802 | def sync(opts, form, saltenv=None):
'''
Sync custom modules into the extension_modules directory
'''
if saltenv is None:
saltenv = ['base']
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret = []
remote = set()
source = salt.utils.url.create('_' + ... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/extmods.py/sync |
2,803 | def test_invalid_annodb_key_str(self):
"""
The invalid key should be mentioned in the KeyError...
"""
try:
self.tdb.annodb['fooBar']
assert 0, "should not reach this point"
except __HOLE__, e:
assert 'fooBar' in str(e) | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/translationDB_test.py/TranslationDB_Test.test_invalid_annodb_key_str |
2,804 | def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False):
"""
Creates the SQL snippet for a column. Used by add_column and add_table.
"""
# If the field hasn't already been told its attribute name, do so.
if not field_prepared:
... | TypeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/firebird.py/DatabaseOperations.column_sql |
2,805 | def _drop_constraints(self, table_name, name, field):
if self.has_check_constraints:
check_constraints = self._constraints_affecting_columns(table_name, [name], "CHECK")
for constraint in check_constraints:
self.execute(self.delete_check_sql % {
'table... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/firebird.py/DatabaseOperations._drop_constraints |
2,806 | def run_only_if_pyutmp_is_available(func):
try:
import pyutmp
except ImportError:
pyutmp = None
try:
import utmp
except __HOLE__:
utmp = None
pred = lambda: pyutmp is not None or utmp is not None
return run_only(func, pred) | ImportError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/users/test/testusers.py/run_only_if_pyutmp_is_available |
2,807 | def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1... | AttributeError | dataset/ETHPy150Open PythonCharmers/python-future/docs/3rd-party-py3k-compat-code/pandas_py3k.py/_OrderedDict.__init__ |
2,808 | def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in itervalues(self.__map):
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except __HOLE__:
pass
dict... | AttributeError | dataset/ETHPy150Open PythonCharmers/python-future/docs/3rd-party-py3k-compat-code/pandas_py3k.py/_OrderedDict.clear |
2,809 | def execute(self):
"""
Runs all cases and records results in `recorder`.
Uses :meth:`setup` and :meth:`resume` with default arguments.
"""
self._setup()
try:
if self.sequential:
self._logger.info('Start sequential evaluation.')
... | StopIteration | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/caseiterdriver.py/CaseIteratorDriver.execute |
2,810 | def _start(self):
""" Start evaluating cases concurrently. """
# Need credentials in case we're using a PublicKey server.
credentials = get_credentials()
# Determine maximum number of servers available.
resources = {
'required_distributions': self._egg_required_distr... | StopIteration | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/caseiterdriver.py/CaseIteratorDriver._start |
2,811 | def _server_ready(self, server):
"""
Responds to asynchronous callbacks during :meth:`execute` to run cases
retrieved from `self._iter`. Results are processed by `recorder`.
Returns True if this server is still in use.
"""
state = server.state
self._logger.debug(... | RuntimeError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/caseiterdriver.py/CaseIteratorDriver._server_ready |
2,812 | def _start_next_case(self, server):
""" Look for the next case and start it. """
if self._todo:
self._logger.debug(' run startup case')
case = self._todo.pop(0)
in_use = self._run_case(case, server)
elif self._rerun:
self._logger.debug(' rer... | StopIteration | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/caseiterdriver.py/CaseIteratorDriver._start_next_case |
2,813 | def InsertVideo(self, album_or_uri, video, filename_or_handle, content_type='image/jpeg'):
"""Copy of InsertPhoto which removes protections since it *should* work"""
try:
assert(isinstance(video, VideoEntry))
except AssertionError:
raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUME... | AssertionError | dataset/ETHPy150Open jackpal/picasawebuploader/main.py/InsertVideo |
2,814 | def _float_or_none(value):
try:
return float(value)
except __HOLE__:
return None | ValueError | dataset/ETHPy150Open seatgeek/graphite-pager/graphitepager/graphite_data_record.py/_float_or_none |
2,815 | def get_by_natural_key(self, hashval=None, **kwargs):
qs = self.filter_by_natural_key(hashval, **kwargs)
real_hashval = qs._hashval
try:
return qs.get()
except MultipleObjectsReturned, error:
raise MultipleObjectsReturned('Duplicate natural keys found! Lookup para... | ObjectDoesNotExist | dataset/ETHPy150Open zbyte64/django-dockit/dockit/schema/manager.py/Manager.get_by_natural_key |
2,816 | def load_app_yaml(self, path=None):
# default to the initialized path set with command args
if path is None:
self.set_app_path(self.app_path)
else:
self.set_app_path(path)
try:
with open(self.app_yaml_path, 'r') as yaml_file:
self.app_... | IOError | dataset/ETHPy150Open glennyonemitsu/MarkupHiveSDK/sdklib/wsgi.py/DynamicDispatcher.load_app_yaml |
2,817 | def __call__(self):
logger.info('Running source code watcher')
while True:
app_path = os.path.abspath(self.path)
css_path = os.path.join(app_path, 'static', 'css')
js_path = os.path.join(app_path, 'static', 'js')
static_files = [f fo... | OSError | dataset/ETHPy150Open glennyonemitsu/MarkupHiveSDK/sdklib/wsgi.py/SourceWatcher.__call__ |
2,818 | def get_dataflow_docstring():
"""Get docstring for Dataflow module and give it an rST title."""
init_file_path = os.path.normpath('./google/cloud/dataflow/__init__.py')
try:
with open(init_file_path, 'r') as init_file:
init_file_contents = init_file.read()
except __HOLE__:
return None
doc_match ... | IOError | dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/setup.py/get_dataflow_docstring |
2,819 | def catkin_main(sysargs):
# Initialize config
try:
initialize_config()
except __HOLE__ as exc:
sys.exit("Failed to initialize config: {0}".format(exc))
# Create a top level parser
parser = argparse.ArgumentParser(
description="catkin command", formatter_class=argparse.RawDes... | RuntimeError | dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/commands/catkin.py/catkin_main |
2,820 | def main(sysargs=None):
try:
catkin_main(sysargs)
except __HOLE__:
print('Interrupted by user!') | KeyboardInterrupt | dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/commands/catkin.py/main |
2,821 | def __getattribute__(self, name):
try:
attr = object.__getattribute__(self, name)
except __HOLE__:
raise AttributeError("'{}' object has no attribute '{}'".format(
self.__class__.__name__, name))
if name == 'close' or name.startswith('_')... | AttributeError | dataset/ETHPy150Open nephics/tornado-couchdb/couch/couch.py/BlockingCouch.__getattribute__ |
2,822 | def test_nullbooleanfield_blank(self):
"""
Regression test for #13071: NullBooleanField should not throw
a validation error when given a value of None.
"""
nullboolean = NullBooleanModel(nbfield=None)
try:
nullboolean.full_clean()
except __HOLE__ as e... | ValidationError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/model_fields/tests.py/BasicFieldTests.test_nullbooleanfield_blank |
2,823 | 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 'pro... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/profitbricks.py/create |
2,824 | def complete(self, text, state):
if text.startswith("#"):
matches = self.reader_matches(text)
elif "." in text:
matches = self.attr_matches(text)
else:
matches = self.global_matches(text)
try:
return matches[state]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open hylang/hy/hy/completer.py/Completer.complete |
2,825 | @contextlib.contextmanager
def completion(completer=None):
delims = "()[]{} "
if not completer:
completer = Completer()
if docomplete:
readline.set_completer(completer.complete)
readline.set_completer_delims(delims)
history = os.path.expanduser("~/.hy-history")
read... | IOError | dataset/ETHPy150Open hylang/hy/hy/completer.py/completion |
2,826 | def key(self, identifier=None, security_level=None):
"""
Tries to find an encryption key, first using the ``identifier`` and
if that fails or isn't provided using the ``security_level``.
Returns ``None`` if nothing matches.
"""
if identifier:
try:
... | KeyError | dataset/ETHPy150Open georgebrock/1pass/onepassword/keychain.py/Keychain.key |
2,827 | def choice_detail(request, app_label, module_name, field_name,
field_val, models):
m, f = lookup_field(app_label, module_name, field_name, models)
try:
label = dict(f.field.choices)[field_val]
except __HOLE__:
raise Http404('Invalid choice value given')
obj_list = m.obj... | KeyError | dataset/ETHPy150Open Alir3z4/django-databrowse/django_databrowse/views.py/choice_detail |
2,828 | def run(self):
self.loop = asyncio.get_event_loop()
self.coro = self.loop.create_server(self.factory, '127.0.0.1', self.port)
self.server = self.loop.run_until_complete(self.coro)
try:
self.loop.run_forever()
except __HOLE__:
pass
finally:
... | KeyboardInterrupt | dataset/ETHPy150Open ekulyk/PythonPusherClient/tests/pusherserver/pusherserverasyncio.py/Pusher.run |
2,829 | def _get_anno_version(self):
"""
Extract the snpEff or VEP version used to annotate the VCF
"""
# default to unknown version
self.args.version = None
if self.args.anno_type == "snpEff":
try:
version_string = self.vcf_reader['SnpEffVersion']['S... | KeyError | dataset/ETHPy150Open arq5x/gemini/gemini/gemini_load_chunk.py/GeminiLoader._get_anno_version |
2,830 | def _get_vep_csq(self, reader):
"""
Test whether the VCF header meets expectations for
proper execution of VEP for use with Gemini.
"""
required = ["Consequence"]
try:
parts = reader["CSQ"]["Description"].strip().replace('"', '').split("Format: ")[-1].split("|... | KeyError | dataset/ETHPy150Open arq5x/gemini/gemini/gemini_load_chunk.py/GeminiLoader._get_vep_csq |
2,831 | def _prepare_variation(self, var, anno_keys):
"""private method to collect metrics for a single variant (var) in a VCF file.
Extracts variant information, variant impacts and extra fields for annotation.
"""
extra_fields = {}
# these metric require that genotypes are present in ... | KeyError | dataset/ETHPy150Open arq5x/gemini/gemini/gemini_load_chunk.py/GeminiLoader._prepare_variation |
2,832 | def test01d_errors(self):
"Testing the Error handlers."
# string-based
print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n"
for err in errors:
try:
g = fromstr(err.wkt)
except (GEOSException, __HOLE__):
pass
print "\nEN... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/gis/tests/test_geos.py/GEOSTest.test01d_errors |
2,833 | def dtype_specs(self):
"""
Return a tuple (python type, c type, numpy typenum) that corresponds
to self.dtype.
This function is used internally as part of C code generation.
"""
try:
return {
'float16': (float, 'npy_float16', 'NPY_FLOAT16'),
... | KeyError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/gpuarray/type.py/GpuArrayType.dtype_specs |
2,834 | def _should_fail(self, f):
try:
f(self.unit_test)
self.fail(
'AssertionError is expected to be raised, but none is raised')
except __HOLE__ as e:
# check if the detail is included in the error object
self.assertIn('first error message:', str(e)) | AssertionError | dataset/ETHPy150Open pfnet/chainer/tests/chainer_tests/testing_tests/test_condition.py/_should_fail |
2,835 | def run(self):
# check repo root for a package.json file
if not os.path.isfile(self.repo_root+"/package.json"):
print("Creating package.json...", file=sys.stderr)
self.create_package_json()
cmds = ["npm", "install", "--progress-false"]
try:
run(cmds,... | OSError | dataset/ETHPy150Open stitchfix/pyxley/pyxley/utils/npm.py/NPM.run |
2,836 | def sort(ctx_name, defaultfield=None, defaultdirection=DEFAULT):
"""Sort queryset found in TemplateResponse context under ``ctx_name``."""
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
... | AttributeError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/sort.py/sort |
2,837 | @task
@write
def add_validation_jobs(pks, job_pk, **kw):
log.info('[%s@None] Adding validation jobs for addons starting at: %s '
' for job: %s'
% (len(pks), pks[0], job_pk))
job = ValidationJob.objects.get(pk=job_pk)
curr_ver = job.curr_max_version.version_int
target_ver = job... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/tasks.py/add_validation_jobs |
2,838 | def load_collectors(paths=None, filter=None):
"""
Scan for collectors to load from path
"""
# Initialize return value
collectors = {}
log = logging.getLogger('diamond')
if paths is None:
return
if isinstance(paths, basestring):
paths = map(str, paths.split(','))
... | SystemExit | dataset/ETHPy150Open Yelp/fullerite/src/diamond/utils/classes.py/load_collectors |
2,839 | def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
... | AttributeError | dataset/ETHPy150Open caktus/django-timepiece/timepiece/utils/__init__.py/add_timezone |
2,840 | def get_wordlist(wordlist_name):
"""
Get and iterator of specified word list.
:param wordlist_name: Word list name
:type wordlist_name: basestring
:return: iterator with each line of file.
:rtype: str
"""
if not isinstance(wordlist_name, str):
raise TypeError("Expected basestri... | IOError | dataset/ETHPy150Open iniqua/plecost/plecost_lib/libs/wordlist.py/get_wordlist |
2,841 | def unique_id_from_node(self, node):
new_key = self.convert_key('pm_addr')
assert new_key is not None
try:
result = node.driver_info[new_key]
except __HOLE__:
# Node cannot be identified
return
if self._has_port:
new_port = self.co... | KeyError | dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/utils/nodes.py/PrefixedDriverInfo.unique_id_from_node |
2,842 | def unique_id_from_node(self, node):
try:
result = super(iBootDriverInfo, self).unique_id_from_node(node)
except __HOLE__:
return
if node.driver_info.get('iboot_relay_id'):
result = '%s#%s' % (result, node.driver_info['iboot_relay_id'])
return result | IndexError | dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/utils/nodes.py/iBootDriverInfo.unique_id_from_node |
2,843 | def _find_node_handler(fields):
try:
driver = fields['pm_type']
except __HOLE__:
raise exception.InvalidNode('pm_type (ironic driver to use) is '
'required', node=fields)
return _find_driver_handler(driver) | KeyError | dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/utils/nodes.py/_find_node_handler |
2,844 | def _get_node_id(node, handler, node_map):
candidates = []
for mac in node.get('mac', []):
try:
candidates.append(node_map['mac'][mac.lower()])
except __HOLE__:
pass
unique_id = handler.unique_id_from_fields(node)
if unique_id:
try:
candidates... | KeyError | dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/utils/nodes.py/_get_node_id |
2,845 | def ValueOf(self, expression, default_value=None, return_type=None):
"""Returns the value of an expression on a document.
Args:
expression: The expression string.
default_value: The value to return if the expression cannot be evaluated.
return_type: The type the expression should evaluate to.... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/search/stub/expression_evaluator.py/ExpressionEvaluator.ValueOf |
2,846 | def setUp(self):
# Create method was not returning the created object with
# the create() method
try:
self.config = Config.objects.get(group='test')
except __HOLE__:
self.config = Config(group='test')
self.config.save()
self.config.values.appe... | DoesNotExist | dataset/ETHPy150Open LeightonStreet/LingoBarter/lingobarter/core/tests/test_models.py/TestConfig.setUp |
2,847 | def abs__file__():
"""Set all module' __file__ attribute to an absolute path"""
for m in sys.modules.values():
if hasattr(m, '__loader__'):
continue # don't mess with a PEP 302-supplied __file__
try:
m.__file__ = os.path.abspath(m.__file__)
except __HOLE_... | AttributeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/abs__file__ |
2,848 | def _init_pathinfo():
"""Return a set containing all existing directory entries from sys.path"""
d = set()
for dir in sys.path:
try:
if os.path.isdir(dir):
dir, dircase = makepath(dir)
d.add(dircase)
except __HOLE__:
continue
... | TypeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/_init_pathinfo |
2,849 | def addpackage(sitedir, name, known_paths):
"""Process a .pth file within the site-packages directory:
For each line in the file, either combine it with sitedir to a path
and add that to known_paths, or execute it if it starts with 'import '.
"""
if known_paths is None:
_init_pat... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/addpackage |
2,850 | def __setup(self):
if self.__lines:
return
data = None
for dir in self.__dirs:
for filename in self.__files:
filename = os.path.join(dir, filename)
try:
fp = file(filename, "rU")
data = fp.re... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/_Printer.__setup |
2,851 | def __call__(self):
self.__setup()
prompt = 'Hit Return for more, or q (and Return) to quit: '
lineno = 0
while 1:
try:
for i in range(lineno, lineno + self.MAXLINES):
print self.__lines[i]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/_Printer.__call__ |
2,852 | def execsitecustomize():
"""Run custom site specific code, if available."""
try:
import sitecustomize
except __HOLE__:
pass | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/execsitecustomize |
2,853 | def execusercustomize():
"""Run custom user specific code, if available."""
try:
import usercustomize
except __HOLE__:
pass | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site.py/execusercustomize |
2,854 | def remove_settings(self, filename, is_dir=False):
full_name = os.path.join(test_dir, filename)
if is_dir:
shutil.rmtree(full_name)
else:
os.remove(full_name)
# Also try to remove the compiled file; if it exists, it could
# mess up later tests that depend... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/admin_scripts/tests.py/AdminScriptTestCase.remove_settings |
2,855 | def __new__(cls, name, bases, attrs):
"""
Checks for an inner ``Meta`` class with a ``mixin_for``
attribute containing the model that this model will be mixed
into. Once found, copy over any model fields and methods onto
the model being mixed into, and return it as the actual cla... | AttributeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/utils/models.py/ModelMixinBase.__new__ |
2,856 | def execute_wf(wf, output_port):
# Save the workflow in a temporary file
temp_wf_fd, temp_wf = tempfile.mkstemp()
try:
f = open(temp_wf, 'w')
f.write(wf)
f.close()
os.close(temp_wf_fd)
# Clean the cache
interpreter = get_default_interpreter()
interpr... | IndexError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/parallelflow/map.py/execute_wf |
2,857 | def _get_last_lobbyist_represent_data(self, data):
try:
last_lobbyist_represent_data = LobbyistRepresentData.objects.filter(scrape_time__isnull=False).latest('scrape_time')
except __HOLE__:
last_lobbyist_represent_data = None
if last_lobbyist_represent_data is not None:
... | ObjectDoesNotExist | dataset/ETHPy150Open ofri/Open-Knesset/lobbyists/scrapers/lobbyist_represent.py/LobbyistRepresentListStorage._get_last_lobbyist_represent_data |
2,858 | def modified(date=None, etag=None):
"""
Checks to see if the page has been modified since the version in the
requester's cache.
When you publish pages, you can include `Last-Modified` and `ETag`
with the date the page was last modified and an opaque token for
the particular version, ... | ImportError | dataset/ETHPy150Open rouge8/20questions/web/http.py/modified |
2,859 | def sync_plans():
"""
Syncronizes all plans from the Stripe API
"""
try:
plans = stripe.Plan.auto_paging_iter()
except __HOLE__:
plans = iter(stripe.Plan.all().data)
for plan in plans:
defaults = dict(
amount=utils.convert_amount_for_db(plan["amount"], plan["... | AttributeError | dataset/ETHPy150Open pinax/pinax-stripe/pinax/stripe/actions/plans.py/sync_plans |
2,860 | def long_description():
"""Return long description from README.rst if it's present
because it doesn't get installed."""
try:
return open(join(dirname(__file__), 'README.rst')).read()
except __HOLE__:
return LONG_DESCRIPTION | IOError | dataset/ETHPy150Open omab/python-social-auth/setup.py/long_description |
2,861 | def update_category_cache(instance):
# NOTE: ATM, we clear the whole cache if a category has been changed.
# Otherwise is lasts to long when the a category has a lot of products
# (1000s) and the shop admin changes a category.
clear_cache()
return
cache.delete("%s-category-breadcrumbs-%s" % (se... | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/caching/listeners.py/update_category_cache |
2,862 | def update_product_cache(instance):
# If the instance is a product with variant or a variant we have to
# delete also the parent and all other variants
if instance.is_variant():
parent = instance.parent
else:
parent = instance
# if product was changed then we have to clear all produ... | TypeError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/caching/listeners.py/update_product_cache |
2,863 | def parse_bits(parser, bits, params, varargs, varkw, defaults,
takes_context, name):
"""
Parse bits for template tag helpers simple_tag and inclusion_tag, in
particular by detecting syntax errors and by extracting positional and
keyword arguments.
"""
if takes_context:
if ... | IndexError | dataset/ETHPy150Open django/django/django/template/library.py/parse_bits |
2,864 | def import_library(name):
"""
Load a Library object from a template tag module.
"""
try:
module = import_module(name)
except ImportError as e:
raise InvalidTemplateLibrary(
"Invalid template library specified. ImportError raised when "
"trying to load '%s': %s... | AttributeError | dataset/ETHPy150Open django/django/django/template/library.py/import_library |
2,865 | def skip_row(self, instance, original):
"""
Returns ``True`` if ``row`` importing should be skipped.
Default implementation returns ``False`` unless skip_unchanged == True.
Override this method to handle skipping rows meeting certain
conditions.
"""
if not self._... | AttributeError | dataset/ETHPy150Open django-import-export/django-import-export/import_export/resources.py/Resource.skip_row |
2,866 | def property_clean(prop, value):
"""Apply Property level validation to value.
Calls .make_value_from_form() and .validate() on the property and catches
exceptions generated by either. The exceptions are converted to
forms.ValidationError exceptions.
Args:
prop: The property to validate against.
val... | ValueError | dataset/ETHPy150Open IanLewis/kay/kay/utils/forms/modelform.py/property_clean |
2,867 | def _normalKeyEvent(key, upDown):
assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'"
try:
if pyautogui.isShiftCharacter(key):
key_code = keyboardMapping[key.lower()]
event = Quartz.CGEventCreateKeyboardEvent(None,
keyboardMapping['... | KeyError | dataset/ETHPy150Open asweigart/pyautogui/pyautogui/_pyautogui_osx.py/_normalKeyEvent |
2,868 | def do_work(job_queue, counter=None):
""" Process work function, read more fetch page jobs
from queue until all jobs are finished
"""
signal.signal(signal.SIGINT, signal.SIG_IGN)
while not job_queue.empty():
try:
job = job_queue.get_nowait()
fetch_result_page(job)
... | KeyboardInterrupt | dataset/ETHPy150Open ikreymer/cdx-index-client/cdx-index-client.py/do_work |
2,869 | def run_workers(num_workers, jobs, shuffle):
""" Queue up all jobs start workers with job_queue
catch KeyboardInterrupt to allow interrupting all workers
Not using Pool to better hande KeyboardInterrupt gracefully
Adapted from example at:
http://bryceboe.com/2012/02/14/python-multiprocessing-pool-an... | KeyboardInterrupt | dataset/ETHPy150Open ikreymer/cdx-index-client/cdx-index-client.py/run_workers |
2,870 | def main():
url_help = """
url to query in the index:
For prefix, use:
http://example.com/*
For domain query, use:
*.example.com
"""
field_list_help = """
select fields to include: eg, --fl url,timestamp
"""
parser = ArgumentParser('CDX Index API Client')
parser.add_a... | NotImplementedError | dataset/ETHPy150Open ikreymer/cdx-index-client/cdx-index-client.py/main |
2,871 | def directory_listing(self, request, folder_id=None, viewtype=None):
clipboard = tools.get_user_clipboard(request.user)
if viewtype == 'images_with_missing_data':
folder = ImagesWithMissingData()
elif viewtype == 'unfiled_images':
folder = UnfiledImages()
elif vie... | ValueError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/media/admin/folder/admin.py/FolderAdmin.directory_listing |
2,872 | @property
def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import g... | ImportError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/media/admin/folder/admin.py/FolderAdmin.owner_search_fields |
2,873 | def response_action(self, request, files_queryset, folders_queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms o... | IndexError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/media/admin/folder/admin.py/FolderAdmin.response_action |
2,874 | def copy_files_and_folders(self, request, files_queryset, folders_queryset):
opts = self.model._meta
app_label = opts.app_label
current_folder = self._get_current_action_folder(
request, files_queryset, folders_queryset)
perms_needed = self._check_copy_perms(
req... | ValueError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/media/admin/folder/admin.py/FolderAdmin.copy_files_and_folders |
2,875 | def get_total_count(self):
"""
Calling `len()` on a QuerySet would execute the whole SELECT.
See `/blog/2012/0124`
"""
di = self.data_iterator
if isinstance(di, QuerySet):
return di.count()
#~ if di is None:
#~ raise Exception("data_iterato... | TypeError | dataset/ETHPy150Open lsaffre/lino/lino/core/tablerequest.py/TableRequest.get_total_count |
2,876 | def parse_req(self, request, rqdata, **kw):
"""Parse the incoming HttpRequest and translate it into keyword
arguments to be used by :meth:`setup`.
The `mt` url param is parsed only when needed. Usually it is
not needed because the `master_class` is constant and known
per actor. ... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/core/tablerequest.py/TableRequest.parse_req |
2,877 | def get_latlng(address):
address_query = urllib.quote(address, '')
values = {
'format' : 'json',
'sensor' : 'false',
'address' : address_query,
}
url = GOOGLE_GEOCODING_API_GEOCODE_URL % values
response = requests.get(url)
data = json.loads(response.text)
try:
... | KeyError | dataset/ETHPy150Open hacktoolkit/hacktoolkit/apis/google/geocode/geocode.py/get_latlng |
2,878 | def reverse_geocode(latitude, longitude):
values = {
'format' : 'json',
'sensor' : 'false',
'latlng' : '%s,%s' % (latitude, longitude,)
}
url = GOOGLE_GEOCODING_API_REVERSE_URL % values
response = requests.get(url)
data = json.loads(response.text)
try:
location = ... | KeyError | dataset/ETHPy150Open hacktoolkit/hacktoolkit/apis/google/geocode/geocode.py/reverse_geocode |
2,879 | def doJoin(self, irc, msg):
channel = msg.args[0]
if ircutils.strEqual(irc.nick, msg.nick):
return
if not self.registryValue('enable', channel):
return
fallthrough = self.registryValue('fallthrough', channel)
def do(type):
cap = ircdb.makeChann... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/AutoMode/plugin.py/AutoMode.doJoin |
2,880 | def _delete_files():
# we don't know the precise name the underlying database uses
# so we use glob to locate all names
for f in glob.glob(_fname + "*"):
try:
os.unlink(f)
except __HOLE__:
pass | OSError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_anydbm.py/_delete_files |
2,881 | def locate_imported_file(self, source_dir, import_path):
""" Locate the imported file in the source directory.
Return the path to the imported file relative to STATIC_ROOT
:param source_dir: source directory
:type source_dir: str
:param import_path: path to the imported file... | ValueError | dataset/ETHPy150Open andreyfedoseev/django-static-precompiler/static_precompiler/compilers/stylus.py/Stylus.locate_imported_file |
2,882 | def find_dependencies(self, source_path):
source = self.get_source(source_path)
source_dir = posixpath.dirname(source_path)
dependencies = set()
imported_files = set()
for import_path in self.find_imports(source):
if import_path.endswith(".styl"):
# @i... | ValueError | dataset/ETHPy150Open andreyfedoseev/django-static-precompiler/static_precompiler/compilers/stylus.py/Stylus.find_dependencies |
2,883 | @access.public
def getRelevantAds(self, params):
AD_LIMIT = 20
def sort_documents_by_url(documents):
return sorted(documents, key=lambda x: x['url'])
# @todo this assumes all URLs returned from Solr will properly urlparse
def group_documents_by_domain(documents):
... | ValueError | dataset/ETHPy150Open memex-explorer/image_space/imagespace/server/imagesearch_rest.py/ImageSearch.getRelevantAds |
2,884 | def _imageSearch(self, params):
limit = params['limit'] if 'limit' in params else '100'
query = params['query'] if 'query' in params else '*:*'
offset = params['offset'] if 'offset' in params else '0'
classifications = json.loads(params['classifications']) if 'classifications' in params ... | ValueError | dataset/ETHPy150Open memex-explorer/image_space/imagespace/server/imagesearch_rest.py/ImageSearch._imageSearch |
2,885 | def printException (ex_args):
data = {}
try:
if isinstance(ex_args, tuple):
data[ex_args[0]] = ex_args[1]
else:
data['state'] = ex_args[0]['state']
if ex_args[0]['data']:
for k,v in ex_args[0]['data'].items():
if k in ['ip',... | KeyError | dataset/ETHPy150Open dpapathanasiou/intelligent-smtp-responder/server/smtp_server.py/printException |
2,886 | def data (cargo):
stream = cargo[0]
email_data = cargo[1]
with_stream_write (stream, '354 End data with \\r\\n.\\r\\n'+cr_lf)
contents = []
client_error = False
subject = None
while 1:
client_msg = with_stream_read (stream)
if client_is_idle(email_data['start']):
... | IndexError | dataset/ETHPy150Open dpapathanasiou/intelligent-smtp-responder/server/smtp_server.py/data |
2,887 | @test.raises(TypeError)
def test_wrap_int(self):
text = int('1' * 80)
try:
new_text = misc.wrap(text, width=5)
except __HOLE__ as e:
self.eq(e.args[0],
"Argument `text` must be one of [str, unicode].")
raise | TypeError | dataset/ETHPy150Open datafolklabs/cement/tests/utils/misc_tests.py/BackendTestCase.test_wrap_int |
2,888 | @test.raises(TypeError)
def test_wrap_none(self):
text = None
try:
new_text = misc.wrap(text, width=5)
except __HOLE__ as e:
self.eq(e.args[0],
"Argument `text` must be one of [str, unicode].")
raise | TypeError | dataset/ETHPy150Open datafolklabs/cement/tests/utils/misc_tests.py/BackendTestCase.test_wrap_none |
2,889 | def oai_process_pcurio(*args):
identifiers = helpers.gather_identifiers(args)
provider_uris, object_uris = helpers.seperate_provider_object_uris(identifiers)
for i, uri in enumerate(provider_uris):
if 'resultadon' in uri:
doc_id = provider_uris[i].replace('http://www.maxwell.vrac.puc-r... | IndexError | dataset/ETHPy150Open CenterForOpenScience/scrapi/scrapi/harvesters/pcurio.py/oai_process_pcurio |
2,890 | def _run_log(self, spec):
def parse_int_list(s):
"""Parses strings like '[1, 2, 3]'."""
s = s.strip()
assert s[0] == '[' and s[-1] == ']', s
if not s[1:-1].strip():
return []
else:
return [int(x) for x in s[1:-1].split(',')]
def split_args(s):
"""Splits 'a, ... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/google/cloud/dataflow/transforms/trigger_test.py/TranscriptTest._run_log |
2,891 | def scan_command_buffers(state):
try:
state.expect(EOF)
except __HOLE__:
raise VimError('trailing characters')
return None, [TokenCommandBuffers(), TokenEof()] | ValueError | dataset/ETHPy150Open guillermooo/Vintageous/ex/parser/scanner_command_buffers.py/scan_command_buffers |
2,892 | def datetime_u(s):
fmt = "%Y-%m-%dT%H:%M:%S"
try:
return _strptime(s, fmt)
except __HOLE__:
try:
# strip utc offset
if s[-3] == ":" and s[-6] in (' ', '-', '+'):
warnings.warn('removing unsupported UTC offset', RuntimeWarning)
s = s[:-... | ValueError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/simplexml.py/datetime_u |
2,893 | def get_namespace_uri(self, ns):
"Return the namespace uri for a prefix"
element = self._element
while element is not None and element.attributes is not None:
try:
return element.attributes['xmlns:%s' % ns].value
except __HOLE__:
element = ... | KeyError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/simplexml.py/SimpleXMLElement.get_namespace_uri |
2,894 | def __call__(self, tag=None, ns=None, children=False, root=False,
error=True, ):
"Search (even in child nodes) and return a child tag by name"
try:
if root:
# return entire document
return SimpleXMLElement(
elements=[self._... | AttributeError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/simplexml.py/SimpleXMLElement.__call__ |
2,895 | def unmarshall(self, types, strict=True):
"Convert to python values the current serialized xml element"
# types is a dict of {tag name: convertion function}
# strict=False to use default type conversion if not specified
# example: types={'p': {'a': int,'b': int}, 'c': [{'d':str}]}
... | TypeError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/simplexml.py/SimpleXMLElement.unmarshall |
2,896 | def _update_ns(self, name):
"""Replace the defined namespace alias with tohse used by the client."""
pref = self.__ns_rx.search(name)
if pref:
pref = pref.groups()[0]
try:
name = name.replace(pref, self.__namespaces_map[pref])
except __HOLE__:
... | KeyError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/contrib/pysimplesoap/simplexml.py/SimpleXMLElement._update_ns |
2,897 | def make_algorithm(self, algorithm_name):
try:
return self.jws_algorithms[algorithm_name]
except __HOLE__:
raise NotImplementedError('Algorithm not supported') | KeyError | dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/itsdangerous.py/JSONWebSignatureSerializer.make_algorithm |
2,898 | def test_all(self):
# Blacklisted modules and packages
blacklist = set([
# Will raise a SyntaxError when compiling the exec statement
'__future__',
])
if not sys.platform.startswith('java'):
# In case _socket fails to build, make this test fail more g... | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test___all__.py/AllTest.test_all |
2,899 | def setup(self):
try:
extension = self._config['extension_url']
KUBERNETES_API_URL = self._config['kubernetes_api_url'] + extension
user = self._config['user']
password = self._config['password']
verify = self._config['verify']
except __HOLE__:... | KeyError | dataset/ETHPy150Open StackStorm/st2contrib/packs/kubernetes/sensors/third_party_resource.py/ThirdPartyResource.setup |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.