Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
1,800 | def generate_tokens(readline):
"""
The generate_tokens() generator requires one argment, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as a string. Alternately,... | StopIteration | dataset/ETHPy150Open babble/babble/include/jython/Lib/tokenize.py/generate_tokens |
1,801 | def mean_tl(tl, surfaces):
try:
tau_axis = tl.ndim - 1
except __HOLE__:
tau_axis = 0
tau = 1.0 / (10.0**(tl/10.0))
return 10.0 * np.log10(1.0 / np.average(tau, tau_axis, surfaces)) | AttributeError | dataset/ETHPy150Open python-acoustics/python-acoustics/acoustics/utils.py/mean_tl |
1,802 | def _cusp_solver(M, parameters):
cache_key = lambda t, p: (t,
p['ksp_type'],
p['pc_type'],
p['ksp_rtol'],
p['ksp_atol'],
p['ksp_max_it'],
... | KeyError | dataset/ETHPy150Open OP2/PyOP2/pyop2/cuda.py/_cusp_solver |
1,803 | def get(self, entity_id=None):
"""HTML GET handler.
Check the query parameters for the ID of the monster to be displayed.
If found, disply that monster using the standard template."""
template_values = self.build_template_values()
if entity_id:
try:
monster = Monster.get... | ValueError | dataset/ETHPy150Open Sagelt/dungeon-world-codex/handlers/monster.py/ViewHandler.get |
1,804 | def DropPrivileges():
"""Attempt to drop privileges if required."""
if config_lib.CONFIG["Server.username"]:
try:
os.setuid(pwd.getpwnam(config_lib.CONFIG["Server.username"]).pw_uid)
except (KeyError, __HOLE__):
logging.exception("Unable to switch to user %s",
config_lib.... | OSError | dataset/ETHPy150Open google/grr/grr/lib/startup.py/DropPrivileges |
1,805 | def resend_confirmation():
"""View for resending an email confirmation email.
"""
form = ResendConfirmationForm(request.form)
if request.method == 'POST':
if form.validate():
clean_email = form.email.data
user = get_user(email=clean_email)
if not user:
... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/framework/auth/views.py/resend_confirmation |
1,806 | @staticmethod
def _new_ingress_rule(ip_protocol, from_port, to_port,
group_id=None, cidr=None):
values = {}
if group_id:
values['group_id'] = group_id
# Open everything if an explicit port range or type/code are not
# specified, but only... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/network/security_group/security_group_base.py/SecurityGroupBase._new_ingress_rule |
1,807 | def load_tests(loader, tests, pattern):
"""Specify which test cases to run."""
del pattern
suite = unittest.TestSuite()
# add all TestCase classes from this (current) module
for attr in globals().values():
try:
if not issubclass(attr, unittest.TestCase):
continue ... | TypeError | dataset/ETHPy150Open django-ddp/django-ddp/tests/django_todos/tests.py/load_tests |
1,808 | def _run(nodes, get_command, env, progress_status):
# nodes: dictionary of node names mapped to node objects
# Node objects can be anything. They're just passed to the get_command function
# get_command: function that takes a node object and returns a command to execute via Popen
# env: name of the environment
... | IOError | dataset/ETHPy150Open sidebolt/chefdash/chefdash/__init__.py/_run |
1,809 | def memoize_lookuptable(func, *args, **kwargs):
"""A decorator that memoizes the results of a decorated function.
Instead of checking if key is in keys, it attempts to access the
property directly, like a typical lookup table."""
funcname = func.__name__
@wraps(func)
def _inner(*args, **kwargs)... | KeyError | dataset/ETHPy150Open christabor/MoAL/MOAL/maths/applied/optimization/memoization.py/memoize_lookuptable |
1,810 | def test_missing_stats_file(self):
stats_file = settings.WEBPACK_LOADER[DEFAULT_CONFIG]['STATS_FILE']
if os.path.exists(stats_file):
os.remove(stats_file)
try:
get_loader(DEFAULT_CONFIG).get_assets()
except __HOLE__ as e:
expected = (
'... | IOError | dataset/ETHPy150Open owais/django-webpack-loader/tests/app/tests/test_webpack.py/LoaderTestCase.test_missing_stats_file |
1,811 | def check_rows(prediction_rows, test_rows):
for row in prediction_rows:
check_row = next(test_rows)
assert len(check_row) == len (row)
for index in range(len(row)):
dot = row[index].find(".")
if dot > 0:
try:
decs = min(len(row[inde... | ValueError | dataset/ETHPy150Open bigmlcom/python/bigml/tests/create_batch_prediction_steps.py/check_rows |
1,812 | def module_has_submodule(package, module_name):
"""See if 'module' is in 'package'."""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
try:
... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/utils/module_loading.py/module_has_submodule |
1,813 | def git_version():
cmd = ['git', 'describe', '--abbrev=4']
try:
proc = sp.Popen(cmd, stdout=sp.PIPE)
stdout = proc.communicate()[0].rstrip('\n')
except __HOLE__:
sys.stderr.write('git not found: leaving __version__ alone\n')
return __version__
if proc.returncode != 0:
... | OSError | dataset/ETHPy150Open gavinbeatty/mkvtomp4/setup.py/git_version |
1,814 | def delete_digram(self):
"""Removes the digram from the hash table."""
try:
if digrams[self.digram()] == self:
digrams.pop(self.digram())
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open ResilientScience/wot/wot/sequitur.py/Symbol.delete_digram |
1,815 | def __init__(self, domain, xmlns, app_id=None):
self.domain = domain
self.xmlns = xmlns
if app_id:
self.app_id = app_id
else:
form = get_form_analytics_metadata(domain, app_id, xmlns)
try:
self.app_id = form['app']['id'] if form else No... | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/display.py/_FormType.__init__ |
1,816 | def getPostgreSQLRootPath():
try:
postgreSQLRootPath = os.environ['ops_postgresqlInstallDIR']
return postgreSQLRootPath
except __HOLE__, e:
return None | KeyError | dataset/ETHPy150Open Esri/ops-server-config/SupportFiles/OpsServerConfig.py/getPostgreSQLRootPath |
1,817 | def __new__(meta, name, bases, dct):
actions = dct.pop('ACTIONS', [])
for on_action, actioned, disconnect in actions:
def on_f(self, f, args=None, kw=None):
args = args if args is not None else tuple()
kw = kw if kw is not None else dict()
cid ... | KeyError | dataset/ETHPy150Open mrterry/yoink/yoink/has_actions.py/ActionableMeta.__new__ |
1,818 | def get_credential(section='default'):
if os.environ.get('TRAVIS_TEST'):
username = os.environ.get('TEST_USER_USERNAME')
password = os.environ.get('TEST_USER_PASSWORD')
if username is None or password is None:
msg = 'No credentials environment variables found.'
raise ... | KeyError | dataset/ETHPy150Open shichao-an/115wangpan/u115/conf.py/get_credential |
1,819 | def test_import_lock_fork(self):
import_started = threading.Event()
fake_module_name = "fake test module"
partial_module = "partial"
complete_module = "complete"
def importer():
imp.acquire_lock()
sys.modules[fake_module_name] = partial_module
... | OSError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_fork1.py/ForkTest.test_import_lock_fork |
1,820 | def format_unencoded(self, tokensource, outfile):
# TODO: add support for background colors
t2n = self.ttype2name
cp = self.commandprefix
if self.full:
realoutfile = outfile
outfile = StringIO()
outfile.write(r'\begin{Verbatim}[commandchars=\\\{\}')
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Pygments-1.3.1/pygments/formatters/latex.py/LatexFormatter.format_unencoded |
1,821 | def testCatchStringException(self):
# str exceptions were removed since 2.6
if sys.version_info >= (2, 6):
return
try:
raise "test"
except "test":
return
except __HOLE__, e:
self.fail(e)
self.fail('"test" was not caught or... | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ExceptionTest.py/ExceptionTest.testCatchStringException |
1,822 | def testSyntax(self):
try:
pass
except KeyError, e:
pass
except (TypeError, LookupError), e:
pass
except:
pass
finally:
pass
try:
a = 1
except:
a = 2
else:
a =... | AttributeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ExceptionTest.py/ExceptionTest.testSyntax |
1,823 | def testAssertionError(self):
try:
assert True
self.assertTrue(True)
except AssertionError, e:
self.fail("Got an unexpected assertion error: %r" % e)
try:
assert False
self.fail("AssertionError expected")
except AssertionError, ... | AssertionError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ExceptionTest.py/ExceptionTest.testAssertionError |
1,824 | def ConfigureLogging(debug_level=logging.INFO,
show_level=True,
stderr=True,
syslog=True,
facility=None):
"""Sets up logging defaults for the root logger.
LaunchDaemons should use syslog and disable stderr (or send it to /dev/null ... | KeyError | dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/gmacpyutil.py/ConfigureLogging |
1,825 | def _RunProcess(cmd, stdinput=None, env=None, cwd=None, sudo=False,
sudo_password=None, background=False, stream_output=False,
timeout=0, waitfor=0):
"""Executes cmd using suprocess.
Args:
cmd: An array of strings as the command to run
stdinput: An optional sting as stdin
... | OSError | dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/gmacpyutil.py/_RunProcess |
1,826 | def GetAirportInfo(include_nearby_networks=False):
"""Returns information about current AirPort connection.
Args:
include_nearby_networks: bool, if True a nearby_networks key will be in
the returned dict with a list of detected SSIDs nearby.
Returns:
dict: key value pairs from CWInterface data. If... | TypeError | dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/gmacpyutil.py/GetAirportInfo |
1,827 | def ReleasePowerAssertion(io_lib, assertion_id):
"""Releases a power assertion.
Assertions are released with IOPMAssertionRelease, however if they are not,
assertions are automatically released when the process exits, dies or
crashes, i.e. a crashed process will not prevent idle sleep indefinitely.
Args:
... | AttributeError | dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/gmacpyutil.py/ReleasePowerAssertion |
1,828 | def IsTextConsole():
"""Checks if console is test only or GUI.
Returns:
True if the console is text-only, False if GUI is available
"""
try:
# see TN2083
security_lib = ctypes.cdll.LoadLibrary(
'/System/Library/Frameworks/Security.framework/Security')
# Security.Framework/Headers/AuthS... | OSError | dataset/ETHPy150Open google/macops/gmacpyutil/gmacpyutil/gmacpyutil.py/IsTextConsole |
1,829 | def luhn(candidate):
"""
Checks a candidate number for validity according to the Luhn
algorithm (used in validation of, for example, credit cards).
Both numeric and string candidates are accepted.
"""
if not isinstance(candidate, basestring):
candidate = str(candidate)
try:
e... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/utils/checksums.py/luhn |
1,830 | def parse(self):
_config = self.read_config(self.config)
for src, path, configsection, key, value in _config:
if ':' in configsection:
sectiongroupname, sectionname = configsection.split(':')
else:
sectiongroupname, sectionname = 'global', configse... | AttributeError | dataset/ETHPy150Open ployground/ploy/ploy/config.py/Config.parse |
1,831 | def testIterators_13_Large(self):
n_iter = 300
n_node = 300
tml = random_node_list(122, n_node, 0.75)
random.seed(0)
p = makeTDInstance()
p.update(dict((t, 1) for t in tml))
# set up a list of iterators
def newIter():
recursive = ... | StopIteration | dataset/ETHPy150Open hoytak/treedict/tests/test_iterators_lists.py/TestIteratorsLists.testIterators_13_Large |
1,832 | def lookup(twitter, user_ids):
"""Resolve an entire list of user ids to screen names."""
users = {}
api_limit = 100
for i in range(0, len(user_ids), api_limit):
fail = Fail()
while True:
try:
portion = lookup_portion(twitter, user_ids[i:][:api_limit])
... | KeyError | dataset/ETHPy150Open sixohsix/twitter/twitter/follow.py/lookup |
1,833 | def follow(twitter, screen_name, followers=True):
"""Get the entire list of followers/following for a user."""
user_ids = []
cursor = -1
fail = Fail()
while True:
try:
portion, cursor = follow_portion(twitter, screen_name, cursor,
foll... | KeyError | dataset/ETHPy150Open sixohsix/twitter/twitter/follow.py/follow |
1,834 | def main(args=sys.argv[1:]):
options = {
'oauth': False,
'followers': True,
'api-rate': False,
'show_id': False
}
try:
parse_args(args, options)
except GetoptError as e:
err("I can't do that, %s." % e)
raise SystemExit(1)
# exit if no user or ... | KeyboardInterrupt | dataset/ETHPy150Open sixohsix/twitter/twitter/follow.py/main |
1,835 | def targets(tgt, tgt_type='range', **kwargs):
'''
Return the targets from a range query
'''
r = seco.range.Range(__opts__['range_server'])
log.debug('Range connection to \'{0}\' established'.format(__opts__['range_server']))
hosts = []
try:
log.debug('Querying range for \'{0}\''.fo... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/roster/range.py/targets |
1,836 | def _find_closest_centroids(self, x):
try:
ceil_key = self.C.ceiling_key(x)
except KeyError:
floor_key = self.C.floor_key(x)
return [self.C[floor_key]]
try:
floor_key = self.C.floor_key(x)
except __HOLE__:
ceil_key = self.C.cei... | KeyError | dataset/ETHPy150Open CamDavidsonPilon/tdigest/tdigest/tdigest.py/TDigest._find_closest_centroids |
1,837 | def __arrayPlugGetItem( self, key ) :
if getattr( self, "enableInputGeneratorCompatibility", False ) :
try :
return Gaffer.ArrayPlug.__originalGetItem( self, key )
except __HOLE__ :
if key == self.getName() :
# Some nodes (I'm looking at you UnionFilter) used to
# name their first child without a nu... | KeyError | dataset/ETHPy150Open ImageEngine/gaffer/startup/Gaffer/inputGeneratorCompatibility.py/__arrayPlugGetItem |
1,838 | def replace_with_repr(plan):
r = repr(plan)
try:
return eval(r)
except (TypeError, __HOLE__, SyntaxError):
print 'Error with repr {r} of plan {p}'.format(r=r, p=plan)
raise | AttributeError | dataset/ETHPy150Open uwescience/raco/raco/replace_with_repr.py/replace_with_repr |
1,839 | def __call__(self, name, args):
""" Send message to each listener.
@param name method name
@param args arguments for message instance
@return None
"""
results = []
try:
messageType = self.messageTypes[name]
listeners = self.listeners[maybe... | KeyError | dataset/ETHPy150Open CarterBain/Medici/ib/opt/dispatcher.py/Dispatcher.__call__ |
1,840 | def unregister(self, listener, *types):
""" Disassociate listener with message types created by this Dispatcher.
@param listener callable to no longer receive messages
@param *types zero or more message types to disassociate with listener
@return True if disassociated with one or more h... | KeyError | dataset/ETHPy150Open CarterBain/Medici/ib/opt/dispatcher.py/Dispatcher.unregister |
1,841 | def pag_story_detail(request, year, month, day, slug,
p_per_page=settings.PAGINATION['P_PER_PAGE'],
orphans=settings.PAGINATION['ORPHANS'],
p_object_name="story_content", template_object_name="story",
template_name="stories/pag_story.html", extra_context={}):
"""
A detail view fo... | ValueError | dataset/ETHPy150Open callowayproject/django-stories/stories/views.py/pag_story_detail |
1,842 | def unregister(self, path, watch_type=None, watcher=None, handler=None):
"""Removes an existing watch or handler.
This unregisters an object's watch and handler callback functions. It
doesn't actually prevent the watch or handler from triggering but it
does remove all references fromo the object and pr... | ValueError | dataset/ETHPy150Open liquidgecka/twitcher/twitcher/zkwrapper.py/ZKWrapper.unregister |
1,843 | def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--rnaseq", default=False, action="store_true",
... | AssertionError | dataset/ETHPy150Open tanghaibao/jcvi/apps/gmap.py/align |
1,844 | def ingest ( self ):
"""Read the stack and ingest"""
# for all specified resolutions
for resolution in reversed(self.proj.datasetcfg.resolutions):
print "Building DB for resolution ", resolution, " imagesize ", self.proj.datasetcfg.imagesz[resolution]
zstart = self.proj.datasetcfg.slicerange[... | IOError | dataset/ETHPy150Open neurodata/ndstore/ingest/catmaid/catmaid.py/CatmaidIngest.ingest |
1,845 | @register.tag
def nickname(_parser, token):
"""Almost the same as nickname filter but the result is cached."""
try:
_, email_address, never_me = token.split_contents()
except __HOLE__:
try:
_, email_address = token.split_contents()
never_me = ''
except ValueError:
raise django.templa... | ValueError | dataset/ETHPy150Open rietveld-codereview/rietveld/codereview/library.py/nickname |
1,846 | @classmethod
def match(cls, item):
try:
return item[cls.field] is None
except __HOLE__:
return True | KeyError | dataset/ETHPy150Open beetbox/beets/beets/dbcore/query.py/NoneQuery.match |
1,847 | def _convert(self, s):
"""Convert a string to a numeric type (float or int).
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
# This is really just a bit of fun premature optimization.
if not s:
return None
... | ValueError | dataset/ETHPy150Open beetbox/beets/beets/dbcore/query.py/NumericQuery._convert |
1,848 | @classmethod
def parse(cls, string):
"""Parse a date and return a `Period` object or `None` if the
string is empty.
"""
if not string:
return None
ordinal = string.count('-')
if ordinal >= len(cls.date_formats):
# Too many components.
... | ValueError | dataset/ETHPy150Open beetbox/beets/beets/dbcore/query.py/Period.parse |
1,849 | def _convert(self, s):
"""Convert a M:SS or numeric string to a float.
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
if not s:
return None
try:
return util.raw_seconds_short(s)
except ValueE... | ValueError | dataset/ETHPy150Open beetbox/beets/beets/dbcore/query.py/DurationQuery._convert |
1,850 | def test_crack2(self):
w = Grammar('root b\n'
'b{7} c\n'
'c 1 "1"\n'
' 1 "2"\n'
' 1 "3"\n'
' 4 "4"')
r = GrammarCracker(w)
for _ in range(10):
g = w.generate()
... | KeyError | dataset/ETHPy150Open blackberry/ALF/alf/fuzz/grammr2_test.py/GrammarTests.test_crack2 |
1,851 | def __getattr__(self, key):
try:
return getattr(self.comparator, key)
except __HOLE__:
raise AttributeError(
'Neither %r object nor %r object associated with %s '
'has an attribute %r' % (
type(self).__name__,
... | AttributeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py/QueryableAttribute.__getattr__ |
1,852 | def create_proxied_attribute(descriptor):
"""Create an QueryableAttribute / user descriptor hybrid.
Returns a new QueryableAttribute type that delegates descriptor
behavior and getattr() to the given descriptor.
"""
# TODO: can move this to descriptor_props if the need for this
# function is r... | AttributeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py/create_proxied_attribute |
1,853 | def get(self, state, dict_, passive=PASSIVE_OFF):
"""Retrieve a value from the given object.
If a callable is assembled on this object's attribute, and
passive is False, the callable will be executed and the
resulting value will be set as the new value for this attribute.
"""
... | KeyError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py/AttributeImpl.get |
1,854 | def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
try:
# TODO: better solution here would be to add
# a "popper" role to collections.py to complement
# "remover".
self.remove(state, dict_, value, initiator, passive=passive)
except (__HOLE... | ValueError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py/CollectionAttributeImpl.pop |
1,855 | def update_parameters():
"""Try to download a new version of the parameter file.
"""
global parameters
if parameters is not None:
return
url = 'https://reprozip-stats.poly.edu/parameters/'
env_var = os.environ.get('REPROZIP_PARAMETERS')
if env_var not in (None, '', '1', 'on', 'enabl... | OSError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip/reprounzip/parameters.py/update_parameters |
1,856 | def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | AssertionError | dataset/ETHPy150Open binux/pyspider/pyspider/result/result_worker.py/ResultWorker.run |
1,857 | def raw_api_call(self, url, parameters={}, http_method="GET", max_timeout=4):
"""
Make an API Call to GitHub
"""
# limit to 1 call per 1.15 seconds
if time.time() - self._fetched <= 1.15:
time.sleep(1.15 - (time.time() - self._fetched))
self._fetched = time.ti... | ValueError | dataset/ETHPy150Open frozenskys/django-github/github/libs/github.py/GithubAPI.raw_api_call |
1,858 | def save(self):
# We go back to the object to read (in order to reapply) the
# permissions which were set on this group, but which are not
# accessible in the wagtail admin interface, as otherwise these would
# be clobbered by this form.
try:
untouchable_permissions =... | ValueError | dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailusers/forms.py/GroupForm.save |
1,859 | def getNewApplication(self, request):
# Creates a new application instance
try:
applicationClass = self.getApplicationClass()
application = applicationClass()
except __HOLE__:
raise ServletException, "getNewApplication failed"
return application | TypeError | dataset/ETHPy150Open rwl/muntjac/muntjac/terminal/gwt/server/application_servlet.py/ApplicationServlet.getNewApplication |
1,860 | def save_files_classification(self):
"""
Save solver, train_val and deploy files to disk
"""
network = cleanedUpClassificationNetwork(self.network, len(self.get_labels()))
data_layers, train_val_layers, deploy_layers = filterLayersByState(network)
### Write train_val fil... | AttributeError | dataset/ETHPy150Open NVIDIA/DIGITS/digits/model/tasks/caffe_train.py/CaffeTrainTask.save_files_classification |
1,861 | def save_files_generic(self):
"""
Save solver, train_val and deploy files to disk
"""
train_image_db = None
train_labels_db = None
val_image_db = None
val_labels_db = None
for task in self.dataset.tasks:
if task.purpose == 'Training Images':
... | AttributeError | dataset/ETHPy150Open NVIDIA/DIGITS/digits/model/tasks/caffe_train.py/CaffeTrainTask.save_files_generic |
1,862 | def get_net(self, epoch=None, gpu=-1):
"""
Returns an instance of caffe.Net
Keyword Arguments:
epoch -- which snapshot to load (default is -1 to load the most recently generated snapshot)
"""
if not self.has_model():
return False
file_to_load = None
... | ImportError | dataset/ETHPy150Open NVIDIA/DIGITS/digits/model/tasks/caffe_train.py/CaffeTrainTask.get_net |
1,863 | def process_request(self, request):
# Determine which theme the user has configured and store in local
# thread storage so that it persists to the custom template loader
try:
_local.theme = request.COOKIES[get_theme_cookie_name()]
except __HOLE__:
_local.theme = ... | KeyError | dataset/ETHPy150Open openstack/horizon/horizon/themes.py/ThemeMiddleware.process_request |
1,864 | def process_response(self, request, response):
try:
delattr(_local, 'theme')
except __HOLE__:
pass
return response | AttributeError | dataset/ETHPy150Open openstack/horizon/horizon/themes.py/ThemeMiddleware.process_response |
1,865 | def get_template_sources(self, template_name):
# If the cookie doesn't exist, set it to the default theme
default_theme = get_default_theme()
theme = getattr(_local, 'theme', default_theme)
this_theme = find_theme(theme)
# If the theme is not valid, check the default theme ...
... | UnicodeDecodeError | dataset/ETHPy150Open openstack/horizon/horizon/themes.py/ThemeTemplateLoader.get_template_sources |
1,866 | def load_template_source(self, template_name, template_dirs=None):
for path in self.get_template_sources(template_name):
try:
with io.open(path, encoding=settings.FILE_CHARSET) as file:
return file.read(), path
except __HOLE__:
pass
... | IOError | dataset/ETHPy150Open openstack/horizon/horizon/themes.py/ThemeTemplateLoader.load_template_source |
1,867 | def _load(self, typ, version):
"""Return class for *typ* and *version*."""
classes = self._get_type_dict()
try:
lst = classes[typ]
dist = lst[0]
groups = lst[1]
klass = dist.load_entry_point(groups[0], typ)
if version is not None and di... | KeyError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/pkg_res_factory.py/PkgResourcesFactory._load |
1,868 | def request(method, url, data=None, headers={}, timeout=None):
host_port = url.split('/')[2]
timeout_set = False
try:
connection = httplib.HTTPConnection(host_port, timeout = timeout)
timeout_set = True
except __HOLE__:
connection = httplib.HTTPConnection(host_port)
with clo... | TypeError | dataset/ETHPy150Open kmike/yandex-maps/yandex_maps/http.py/request |
1,869 | def test_TestFunctionality(self):
bucket = PropBucket()
try:
bucket.prop.value = bucket.prop.value + 0
except __HOLE__:
pass
else:
assert False, "PropBucket is not working" | AssertionError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_evalorder.py/EvaluationOrder.test_TestFunctionality |
1,870 | def _GetDecrypter(self):
"""Retrieves a decrypter.
Returns:
A decrypter object (instance of encryptions.Decrypter).
Raises:
IOError: if the decrypter cannot be initialized.
"""
try:
credentials = resolver.Resolver.key_chain.GetCredentials(self._path_spec)
return encryption_... | ValueError | dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/file_io/encrypted_stream_io.py/EncryptedStream._GetDecrypter |
1,871 | def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the ISY994 platform."""
# pylint: disable=protected-access
logger = logging.getLogger(__name__)
devs = []
# Verify connection
if ISY is None or not ISY.connected:
logger.error('A connection has not been made to ... | KeyError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/sensor/isy994.py/setup_platform |
1,872 | @Text('teardown')
def teardown (self, reactor, service, command):
try:
descriptions,command = self.parser.extract_neighbors(command)
_,code = command.split(' ',1)
for key in reactor.peers:
for description in descriptions:
if reactor.match_neighbor(description,key):
reactor.peers[key].teardown(int(cod... | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/teardown |
1,873 | @Text('announce watchdog')
def announce_watchdog (self, reactor, service, command):
def callback (name):
# XXX: move into Action
for neighbor in reactor.configuration.neighbors:
reactor.configuration.neighbors[neighbor].rib.outgoing.announce_watchdog(name)
yield False
reactor.route_update = True
reactor... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_watchdog |
1,874 | @Text('withdraw watchdog')
def withdraw_watchdog (self, reactor, service, command):
def callback (name):
# XXX: move into Action
for neighbor in reactor.configuration.neighbors:
reactor.configuration.neighbors[neighbor].rib.outgoing.withdraw_watchdog(name)
yield False
reactor.route_update = True
reactor... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/withdraw_watchdog |
1,875 | @Text('flush route')
def flush_route (self, reactor, service, command):
def callback (self, peers):
self.log_message("Flushing routes for %s" % ', '.join(peers if peers else []) if peers is not None else 'all peers')
yield True
reactor.route_update = True
reactor.answer(service,'done')
try:
descriptions,c... | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/flush_route |
1,876 | @Text('announce route')
def announce_route (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reacto... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_route |
1,877 | @Text('withdraw route')
def withdraw_route (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reacto... | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/withdraw_route |
1,878 | @Text('announce vpls')
def announce_vpls (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reactor.... | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_vpls |
1,879 | @Text('withdraw vpls')
def withdraw_vpls (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reactor.... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/withdraw_vpls |
1,880 | @Text('announce attributes')
def announce_attributes (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
... | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_attributes |
1,881 | @Text('withdraw attributes')
def withdraw_attribute (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/withdraw_attribute |
1,882 | @Text('announce flow')
def announce_flow (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reactor.... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_flow |
1,883 | @Text('withdraw flow')
def withdraw_flow (self, reactor, service, line):
def callback ():
try:
descriptions,command = self.parser.extract_neighbors(line)
peers = reactor.match_neighbors(descriptions)
if not peers:
self.log_failure('no neighbor matching the command : %s' % command,'warning')
reactor.... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/withdraw_flow |
1,884 | @Text('announce eor')
def announce_eor (self, reactor, service, command):
def callback (self, command, peers):
family = self.parser.api_eor(command)
if not family:
self.log_failure("Command could not parse eor : %s" % command)
reactor.answer(service,'error')
yield True
return
reactor.configuration.i... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_eor |
1,885 | @Text('announce route-refresh')
def announce_refresh (self, reactor, service, command):
def callback (self, command, peers):
refresh = self.parser.api_refresh(command)
if not refresh:
self.log_failure("Command could not parse flow in : %s" % command)
reactor.answer(service,'error')
yield True
return
... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_refresh |
1,886 | @Text('announce operational')
def announce_operational (self, reactor, service, command):
def callback (self, command, peers):
operational = self.parser.api_operational(command)
if not operational:
self.log_failure("Command could not parse operational command : %s" % command)
reactor.answer(service,'error')
... | IndexError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/api/command/text.py/announce_operational |
1,887 | @classmethod
def get_current_request(cls):
try:
return cls._threadlocal.request
except __HOLE__:
return None | AttributeError | dataset/ETHPy150Open msiedlarek/wiring/example/guestbook/application.py/Application.get_current_request |
1,888 | def updateWebmapService(self, webmapId, oldUrl, newUrl, folderID=None):
try:
params = urllib.urlencode({'token' : self.user.token,
'f' : 'json'})
print 'Getting Info for: ' + webmapId
#Get the item data
reqUrl = self.user.por... | ValueError | dataset/ETHPy150Open Esri/ago-tools/agoTools/utilities.py/Utilities.updateWebmapService |
1,889 | def updateItemUrl(self, itemId, oldUrl, newUrl, folderID=None):
'''
Use this to update the URL for items such as Map Services.
The oldUrl parameter is required as a check to ensure you are not
accidentally changing the wrong item or url.
This can also replace part of a URL. The t... | ValueError | dataset/ETHPy150Open Esri/ago-tools/agoTools/utilities.py/Utilities.updateItemUrl |
1,890 | def updatewebmapversionAGX(self, webmapId, folderID=None):
'''Update the web map version from 1.9x to 1.7x so that the new web maps can be opened in ArcGIS Explorer Online.'''
try:
params = urllib.urlencode({'token' : self.user.token,
'f' : 'json'})
... | ValueError | dataset/ETHPy150Open Esri/ago-tools/agoTools/utilities.py/Utilities.updatewebmapversionAGX |
1,891 | def __getattr__(self, key):
if is_instrumented(self, key):
return get_attribute(self, key)
else:
try:
return self._goofy_dict[key]
except __HOLE__:
raise AttributeError(key) | KeyError | dataset/ETHPy150Open zzzeek/sqlalchemy/examples/custom_attributes/custom_management.py/MyClass.__getattr__ |
1,892 | def extract_component(self, name, action, default_entry_point_creator=None):
"""Return the class + component info to use for doing the action w/the component."""
try:
# Use a copy instead of the original since we will be
# modifying this dictionary which may not be wanted for fut... | KeyError | dataset/ETHPy150Open openstack/anvil/anvil/distro.py/Distro.extract_component |
1,893 | def run():
"""
We reorganized our categories:
https://bugzilla.mozilla.org/show_bug.cgi?id=854499
Usage::
python -B manage.py runscript migrations.575-reorganize-cats
"""
all_cats = Category.objects.filter(type=amo.ADDON_WEBAPP)
# (1) "Entertainment & Sports" becomes "Enter... | IndexError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/migrations/575-reorganize-cats.py/run |
1,894 | def on_message(self, data):
try:
data = json_decode(data)
except __HOLE__:
self._die(log_message='Unable to decode json')
if type(data).__name__ != 'dict' or 'method' not in data:
self._die(log_message='data is not a dict or no key "method" in data dict found... | ValueError | dataset/ETHPy150Open ierror/BeautifulMind.io/beautifulmind/mindmaptornado/handlers.py/MindmapWebSocketHandler.on_message |
1,895 | def on_close(self):
for map_pk in self._maps_participants.keys():
if self in self._maps_participants.get(map_pk, []):
self._lock.acquire()
# remove client from map
try:
self._maps_participants[map_pk].remove(self)
e... | KeyError | dataset/ETHPy150Open ierror/BeautifulMind.io/beautifulmind/mindmaptornado/handlers.py/MindmapWebSocketHandler.on_close |
1,896 | def _parse(self, is_source, lang_rules):
"""
Parses Qt file and exports all entries as GenericTranslations.
"""
def clj(s, w):
return s[:w].replace("\n", " ").ljust(w)
if lang_rules:
nplural = len(lang_rules)
else:
nplural = self.langu... | StopIteration | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/resources/formats/qt.py/LinguistHandler._parse |
1,897 | def test_max_recursion_error(self):
"""
Overriding a method on a super class and then calling that method on
the super class should not trigger infinite recursion. See #17011.
"""
try:
super(ClassDecoratedTestCase, self).test_max_recursion_error()
except __HO... | RuntimeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/settings_tests/tests.py/ClassDecoratedTestCase.test_max_recursion_error |
1,898 | def main(tests=None, testdir=None, verbose=0, quiet=False,
exclude=False, single=False, randomize=False, fromfile=None,
findleaks=False, use_resources=None, trace=False, coverdir='coverage',
runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
expected=False, memo=None... | KeyboardInterrupt | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/regrtest.py/main |
1,899 | def runtest_inner(test, verbose, quiet, test_times,
testdir=None, huntrleaks=False, junit_xml_dir=None):
test_support.unload(test)
if not testdir:
testdir = findtestdir()
if verbose:
capture_stdout = None
else:
capture_stdout = cStringIO.StringIO()
from tes... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/regrtest.py/runtest_inner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.