Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
7,300 | def _is_installed(self, fullname):
try:
self._import_module(fullname)
return True
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open nvbn/import_from_github_com/github_com/__init__.py/GithubComLoader._is_installed |
7,301 | def cp(src, dst, verbose=True):
if verbose:
echo('Copying: %s -> %s' % (os.path.basename(src), os.path.basename(dst)))
try:
copy(src, dst)
except (ShError, __HOLE__) as e:
error(str(e))
# pylint: enable=C0103
# pylint: disable=C0103 | IOError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/cp |
7,302 | def rm(filename, verbose=True):
if verbose:
echo('Removing: %s' % filename)
try:
os.remove(filename)
except __HOLE__ as _:
pass
# pylint: enable=C0103 | OSError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/rm |
7,303 | def mkdir(path, verbose=True):
if verbose:
echo('Creating: %s' % path)
try:
os.makedirs(path)
except __HOLE__ as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise | OSError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/mkdir |
7,304 | def rmdir(path, verbose=True):
def _handle_remove_readonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
func(path)
else:
raise
... | OSError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/rmdir |
7,305 | def command_devserver_js(uglifyjs=None):
uglifyjs = uglifyjs or 'external/uglifyjs/bin/uglifyjs'
def compactor(dev_filename, rel_filename):
# Use compactor to generate release version.
echo('Compacting: %s -> %s' % (dev_filename, rel_filename))
rc = call('node %s -o %s %s' % (uglifyjs, ... | IOError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/command_devserver_js |
7,306 | def command_devserver_css(yuicompressor=None):
yuicompressor = yuicompressor or 'external/yuicompressor/yuicompressor-2.4.2/yuicompressor-2.4.2.jar'
def compactor(dev_filename, rel_filename):
# Use compactor to generate release version.
echo('Compacting: %s -> %s' % (dev_filename, rel_filename)... | IOError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/command_devserver_css |
7,307 | def command_devserver_html():
def compactor(dev_filename, rel_filename):
# Use compactor to generate release version.
echo('Compacting: %s -> %s' % (dev_filename, rel_filename))
source_data = open(dev_filename, 'r').read()
try:
# Verify that the html file is correct
... | IOError | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/command_devserver_html |
7,308 | def command_devserver(args):
# Devserver requires release Javascript and CSS
if args.compile:
command_devserver_js(args.uglifyjs)
command_devserver_css(args.yuicompressor)
command_devserver_html()
if args.development:
start_cmd = 'paster serve --reload development.ini'
e... | KeyboardInterrupt | dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/local_server.py/command_devserver |
7,309 | def _create_sequences(self, func, iterable, chunksize, collector = None):
"""
Create the WorkUnit objects to process and pushes them on the
work queue. Each work unit is meant to process a slice of
iterable of size chunksize. If collector is specified, then
the ApplyResult object... | StopIteration | dataset/ETHPy150Open serverdensity/sd-agent/checks/libs/thread_pool.py/Pool._create_sequences |
7,310 | def next(self, timeout=None):
"""Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job"""
try:
apply_result = self._collector._get_result(self._idx, timeout)
except __HOLE__:
# Reset for nex... | IndexError | dataset/ETHPy150Open serverdensity/sd-agent/checks/libs/thread_pool.py/CollectorIterator.next |
7,311 | def _get_result(self, idx, timeout=None):
"""Called by the CollectorIterator object to retrieve the
result's values one after another, in the order the results have
become available.
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling ... | IndexError | dataset/ETHPy150Open serverdensity/sd-agent/checks/libs/thread_pool.py/UnorderedResultCollector._get_result |
7,312 | def _test():
"""Some tests"""
import thread
import time
def f(x):
return x*x
def work(seconds):
print "[%d] Start to work for %fs..." % (thread.get_ident(), seconds)
time.sleep(seconds)
print "[%d] Work done (%fs)." % (thread.get_ident(), seconds)
return "%d... | IOError | dataset/ETHPy150Open serverdensity/sd-agent/checks/libs/thread_pool.py/_test |
7,313 | def Validate(self, value, key=None):
"""Validates a timezone."""
if value is None:
return
if not isinstance(value, basestring):
raise TypeError('timezone must be a string, not \'%r\'' % type(value))
if pytz is None:
return value
try:
pytz.timezone(value)
except pytz.Unk... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/croninfo.py/TimezoneValidator.Validate |
7,314 | def get_system_username():
"""
Try to determine the current system user's username.
:returns: The username as a unicode string, or an empty string if the
username could not be determined.
"""
try:
result = getpass.getuser()
except (__HOLE__, KeyError):
# KeyError will be... | ImportError | dataset/ETHPy150Open django/django/django/contrib/auth/management/__init__.py/get_system_username |
7,315 | def get_default_username(check_db=True):
"""
Try to determine the current system user's username to use as a default.
:param check_db: If ``True``, requires that the username does not match an
existing ``auth.User`` (otherwise returns an empty string).
:returns: The username, or an empty string... | UnicodeDecodeError | dataset/ETHPy150Open django/django/django/contrib/auth/management/__init__.py/get_default_username |
7,316 | def exists(self, path):
try:
self._sftp.lstat(path)
return True
except __HOLE__:
return False | IOError | dataset/ETHPy150Open openstack/fuel-devops/devops/helpers/ssh_client.py/SSHClient.exists |
7,317 | def isfile(self, path):
try:
attrs = self._sftp.lstat(path)
return attrs.st_mode & stat.S_IFREG != 0
except __HOLE__:
return False | IOError | dataset/ETHPy150Open openstack/fuel-devops/devops/helpers/ssh_client.py/SSHClient.isfile |
7,318 | def isdir(self, path):
try:
attrs = self._sftp.lstat(path)
return attrs.st_mode & stat.S_IFDIR != 0
except __HOLE__:
return False | IOError | dataset/ETHPy150Open openstack/fuel-devops/devops/helpers/ssh_client.py/SSHClient.isdir |
7,319 | def parse(self, bibtex_contents):
ret = []
cleaned_string = bibtex_contents.replace("\&", "").replace("%", "").strip()
entries = ["@"+entry for entry in cleaned_string.split("@") if entry]
biblio_list = self._parse_bibtex_entries(entries)
for biblio in biblio_list:
p... | AttributeError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/bibtex.py/Bibtex.parse |
7,320 | def forwards(self, orm):
# Removing unique constraint on 'KeyValue', fields ['language', 'digest']
try:
db.delete_unique('datatrans_keyvalue', ['language', 'digest'])
except __HOLE__:
print " WARNING: current index didn't exist"
# Adding field 'KeyValue... | ValueError | dataset/ETHPy150Open hzlf/openbroadcast/website/apps/datatrans/migrations/0003_auto__add_field_keyvalue_content_type__add_field_keyvalue_object_id__a.py/Migration.forwards |
7,321 | def get_owner_username(domain, owner_type, facility_id):
if not owner_type:
return ''
facility_index_by_domain = indexed_facilities()
try:
return facility_index_by_domain[domain][facility_id][owner_type]
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/custom/_legacy/hsph/tasks.py/get_owner_username |
7,322 | def get_group_id(domain, owner_type, facility_id):
owner_username = get_owner_username(domain, owner_type, facility_id)
try:
return INDEXED_GROUPS[domain][owner_username]._id
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/custom/_legacy/hsph/tasks.py/get_group_id |
7,323 | def __add__(self, other):
try:
return theano.tensor.basic.add(self, other)
# We should catch the minimum number of exception here.
# Otherwise this will convert error when Theano flags
# compute_test_value is used
# Evidently, we need to catch NotImplementedError
... | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__add__ |
7,324 | def __sub__(self, other):
# See explanation in __add__ for the error catched
# and the return value in that case
try:
return theano.tensor.basic.sub(self, other)
except (__HOLE__, AsTensorError):
return NotImplemented | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__sub__ |
7,325 | def __mul__(self, other):
# See explanation in __add__ for the error catched
# and the return value in that case
try:
return theano.tensor.mul(self, other)
except (__HOLE__, AsTensorError):
return NotImplemented | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__mul__ |
7,326 | def __div__(self, other):
# See explanation in __add__ for the error catched
# and the return value in that case
try:
return theano.tensor.basic.div_proxy(self, other)
except IntegerDivisionError:
# This is to raise the exception that occurs when trying to divide
... | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__div__ |
7,327 | def __pow__(self, other):
# See explanation in __add__ for the error catched
# adn the return value in that case
try:
return theano.tensor.basic.pow(self, other)
except (__HOLE__, AsTensorError):
return NotImplemented | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__pow__ |
7,328 | def __mod__(self, other):
# See explanation in __add__ for the error catched
# adn the return value in that case
try:
return theano.tensor.basic.mod_check(self, other)
except ComplexError:
# This is to raise the exception that occurs when trying to compute
... | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__mod__ |
7,329 | def transpose(self, *axes):
"""
Returns
-------
object
`tensor.transpose(self, axes)` or `tensor.transpose(self, axes[0])`.
If only one `axes` argument is provided and it is iterable, then it is
assumed to be the entire axes tuple, and passed intact to
... | TypeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.transpose |
7,330 | def __iter__(self):
try:
for i in xrange(theano.tensor.basic.get_vector_length(self)):
yield self[i]
except __HOLE__:
# This prevents accidental iteration via builtin.sum(self)
raise TypeError(('TensorType does not support iteration. '
... | TypeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/_tensor_py_operators.__iter__ |
7,331 | def _get_sum(self):
"""Compute sum of non NaN / Inf values in the array."""
try:
return self._sum
except __HOLE__:
self._sum = self.no_nan.sum()
# The following 2 lines are needede as in Python 3.3 with NumPy
# 1.7.1, numpy.ndarray and numpy.memmap... | AttributeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/TensorConstantSignature._get_sum |
7,332 | def _get_no_nan(self):
try:
return self._no_nan
except __HOLE__:
nan_mask = numpy.isnan(self[1])
if nan_mask.any():
self._no_nan = numpy.ma.masked_array(self[1], nan_mask)
self.has_nan = True
else:
self._no_n... | AttributeError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/var.py/TensorConstantSignature._get_no_nan |
7,333 | def get_child_index(self, key):
try:
return self.get_child_keys().index(key)
except __HOLE__:
errorstring = ("Can't find key %s in ParentNode %s\n" +
"ParentNode items: %s")
raise TreeWidgetError(errorstring % (key, self.get_key(),
... | ValueError | dataset/ETHPy150Open AnyMesh/anyMesh-Python/example/urwid/treetools.py/ParentNode.get_child_index |
7,334 | def start(self):
""" Run the server. """
# Bind to the UDP socket.
# IPv4 only
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setblocking(0)
try:
self.socket.bind(self.address)
except socket.gaierror:
if self.add... | KeyboardInterrupt | dataset/ETHPy150Open serverdensity/sd-agent/dogstatsd.py/Server.start |
7,335 | def qapply_Mul(e, **options):
ip_doit = options.get('ip_doit', True)
args = list(e.args)
# If we only have 0 or 1 args, we have nothing to do and return.
if len(args) <= 1 or not isinstance(e, Mul):
return e
rhs = args.pop()
lhs = args.pop()
# Make sure we have two non-commutativ... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/physics/quantum/qapply.py/qapply_Mul |
7,336 | def deploy_service(
service,
instance,
marathon_jobid,
config,
client,
bounce_method,
drain_method_name,
drain_method_params,
nerve_ns,
bounce_health_params,
soa_dir,
):
"""Deploy the service to marathon, either directly or via a bounce if needed.
Called by setup_serv... | KeyError | dataset/ETHPy150Open Yelp/paasta/paasta_tools/setup_marathon_job.py/deploy_service |
7,337 | def main():
"""Attempt to set up the marathon service instance given.
Exits 1 if the deployment failed.
This is done in the following order:
- Load the marathon configuration
- Connect to marathon
- Load the service instance's configuration
- Create the complete marathon job configuration
... | KeyError | dataset/ETHPy150Open Yelp/paasta/paasta_tools/setup_marathon_job.py/main |
7,338 | def load_floorc_json():
# Expose a few settings for curious users to tweak
s = {
'expert_mode': False,
'debug': False,
}
try:
with open(G.FLOORC_JSON_PATH, 'r') as fd:
floorc_json = fd.read()
except IOError as e:
if e.errno == errno.ENOENT:
ret... | ValueError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/load_floorc_json |
7,339 | def _set_timeout(func, timeout, repeat, *args, **kwargs):
timeout_id = set_timeout._top_timeout_id
if timeout_id > 100000:
set_timeout._top_timeout_id = 0
else:
set_timeout._top_timeout_id += 1
try:
from . import api
except __HOLE__:
import api
@api.send_errors
... | ImportError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/_set_timeout |
7,340 | def is_shared(p):
if not G.AGENT or not G.AGENT.joined_workspace:
return False
p = unfuck_path(p)
try:
if to_rel_path(p).find('../') == 0:
return False
except __HOLE__:
return False
return True | ValueError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/is_shared |
7,341 | def read_floo_file(path):
floo_file = os.path.join(path, '.floo')
info = {}
try:
floo_info = open(floo_file, 'rb').read().decode('utf-8')
info = json.loads(floo_info)
except (IOError, __HOLE__):
pass
except Exception as e:
msg.warn('Couldn\'t read .floo file: ', floo... | OSError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/read_floo_file |
7,342 | def get_persistent_data(per_path=None):
per_data = {'recent_workspaces': [], 'workspaces': {}}
per_path = per_path or os.path.join(G.BASE_DIR, 'persistent.json')
try:
per = open(per_path, 'rb')
except (IOError, __HOLE__):
msg.debug('Failed to open ', per_path, '. Recent workspace list wi... | OSError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/get_persistent_data |
7,343 | def rm(path):
"""removes path and dirs going up until a OSError"""
os.remove(path)
try:
os.removedirs(os.path.split(path)[0])
except __HOLE__:
pass | OSError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/rm |
7,344 | def mkdir(path):
try:
os.makedirs(path)
except __HOLE__ as e:
if e.errno != errno.EEXIST:
editor.error_message('Cannot create directory {0}.\n{1}'.format(path, str_e(e)))
raise | OSError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/mkdir |
7,345 | def _unwind_generator(gen_expr, cb=None, res=None):
try:
while True:
maybe_func = res
args = []
# if the first arg is callable, we need to call it (and assume the last argument is a callback)
if type(res) == tuple:
maybe_func = len(res) and res... | StopIteration | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/utils.py/_unwind_generator |
7,346 | def read_min_cells(self, ids):
'''reads cells and cache only the minimum information necessary to compute compatibility
checks. The reason is to save memory in the server.
This funcion is only called by RefTranslator.get_published_min_refs, that is only called
by CompatibilityClosureBuil... | KeyError | dataset/ETHPy150Open biicode/bii-server/store/mem_server_store.py/MemServerStore.read_min_cells |
7,347 | def __init__(self):
try:
self.config = yaml.load(open(sys.argv[1]))
except __HOLE__:
print('Error: not specify config file')
exit(1)
self.dump_cmd = 'mysqldump -h {host} -P {port} -u {user} --password={password} {db} {table} ' \
'--def... | IndexError | dataset/ETHPy150Open zhongbiaodev/py-mysql-elasticsearch-sync/es_sync/__init__.py/ElasticSync.__init__ |
7,348 | def _formatter(self, data):
"""
format every field from xml, according to parsed table structure
"""
for item in data:
for field, serializer in self.table_structure.items():
if item['doc'][field]:
try:
item['doc'][fi... | ValueError | dataset/ETHPy150Open zhongbiaodev/py-mysql-elasticsearch-sync/es_sync/__init__.py/ElasticSync._formatter |
7,349 | def _parse_and_remove(self, f, path):
"""
snippet from python cookbook, for parsing large xml file
"""
path_parts = path.split('/')
doc = iterparse(f, ('start', 'end'), recover=False, encoding='utf-8', huge_tree=True)
# Skip the root element
next(doc)
tag_... | IndexError | dataset/ETHPy150Open zhongbiaodev/py-mysql-elasticsearch-sync/es_sync/__init__.py/ElasticSync._parse_and_remove |
7,350 | def got_message(self, connection, message):
c = self.connections[connection]
t = message[0]
if t == BITFIELD and c.got_anything:
connection.close()
return
c.got_anything = True
if (t in [CHOKE, UNCHOKE, INTERESTED, NOT_INTERESTED] and
... | ValueError | dataset/ETHPy150Open Piratenfraktion-Berlin/OwnTube/videoportal/BitTornadoABC/BitTornado/BT1/Connecter.py/Connecter.got_message |
7,351 | def set_geometry(self, col, drop=False, inplace=False, crs=None):
"""
Set the GeoDataFrame geometry using either an existing column or
the specified input. By default yields a new object.
The original geometry column is replaced with the input.
Parameters
----------
... | KeyError | dataset/ETHPy150Open geopandas/geopandas/geopandas/geodataframe.py/GeoDataFrame.set_geometry |
7,352 | def __init__(self, *args, **kwargs):
super(to_dossier_store, self).__init__(*args, **kwargs)
kvl = kvlayer.client()
feature_indexes = None
try:
conf = yakonfig.get_global_config('dossier.store')
feature_indexes = conf['feature_indexes']
except __HOLE__:
... | KeyError | dataset/ETHPy150Open dossier/dossier.models/dossier/models/etl/interface.py/to_dossier_store.__init__ |
7,353 | def uni(s, encoding=None):
# unicode string feat
if not isinstance(s, unicode):
try:
return unicode(s, encoding)
except:
try:
return unicode(s, 'utf-8')
except __HOLE__:
return unicode(s, 'latin-1')
return s | UnicodeDecodeError | dataset/ETHPy150Open dossier/dossier.models/dossier/models/etl/interface.py/uni |
7,354 | @classmethod
def conf(cls):
logger.debug("Preparing config for snapshot")
nodes = db().query(Node).filter(
Node.status.in_(['ready', 'provisioned', 'deploying', 'error'])
).all()
dump_conf = deepcopy(settings.DUMP)
for node in nodes:
if node.cluster i... | KeyError | dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/task/task.py/DumpTask.conf |
7,355 | @cassiopeia.type.core.common.lazyproperty
def runes(self):
"""
Returns:
list<Rune>: the runes in this rune page
"""
runes = {}
for slot in self.data.slots:
try:
runes[slot.runeId] += 1
except __HOLE__:
runes[... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/type/core/summoner.py/RunePage.runes |
7,356 | def get_range(self, name, min_value=None, max_value=None, default=0):
"""Parses the given int argument, limiting it to the given range.
Args:
name: the name of the argument
min_value: the minimum int value of the argument (if any)
max_value: the maximum int value of the argument (if any)
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/webapp/mock_webapp.py/MockRequest.get_range |
7,357 | def _set_launcher_affinity(self):
try:
self._launcher_pid = self.device.get_pids_of('com.android.launcher')[0]
result = self.device.execute('taskset -p {}'.format(self._launcher_pid), busybox=True, as_root=True)
self._old_launcher_affinity = int(result.split(':')[1].strip(), ... | IndexError | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/workloads/applaunch/__init__.py/ApplaunchWorkload._set_launcher_affinity |
7,358 | def render(self, context, instance, placeholder):
"""
Return the context to render a DialogFormPlugin
"""
form_type = instance.glossary.get('form_type')
if form_type:
# prevent a malicious database entry to import an ineligible file
form_type = AUTH_FORM_T... | IndexError | dataset/ETHPy150Open awesto/django-shop/shop/cascade/auth.py/ShopAuthenticationPlugin.render |
7,359 | @register.tag('bbcode')
def do_bbcode_rendering(parser, token):
"""
This will render a string containing bbcodes to the corresponding HTML markup.
Usage::
{% bbcode "[b]hello world![/b]" %}
You can use variables instead of constant strings to render bbcode stuff::
{% bbcode content... | IndexError | dataset/ETHPy150Open ellmetha/django-precise-bbcode/precise_bbcode/templatetags/bbcode_tags.py/do_bbcode_rendering |
7,360 | def request(self, endpoint, method='GET', blog_url=None,
extra_endpoints=None, params=None):
params = params or {}
method = method.lower()
if not method in ('get', 'post'):
raise TumblpyError('Method must be of GET or POST')
url = self.api_url # http://api.... | AttributeError | dataset/ETHPy150Open michaelhelmick/python-tumblpy/tumblpy/api.py/Tumblpy.request |
7,361 | def test_check_is_fitted():
# Check is ValueError raised when non estimator instance passed
assert_raises(ValueError, check_is_fitted, ARDRegression, "coef_")
assert_raises(TypeError, check_is_fitted, "SVR", "support_")
ard = ARDRegression()
svr = SVR()
try:
assert_raises(NotFittedErro... | AttributeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/utils/tests/test_validation.py/test_check_is_fitted |
7,362 | def get_n_rooms(self):
try:
return len(self.db.request("GET", ("/%s_rooms/_design/by_msg_count/"
"_view/by_msg_count/") % self.couchdb_prefix)["rows"])
except __HOLE__:
return 0 | KeyError | dataset/ETHPy150Open sfstpala/Victory-Chat/modules/chat.py/ChatMixIn.get_n_rooms |
7,363 | def get(self, ftype, fname):
try:
return self.config_files.read(ftype, fname)
except __HOLE__:
return {} | IOError | dataset/ETHPy150Open locaweb/haproxy-manager/src/haproxy_manager/manager.py/Manager.get |
7,364 | def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'dj... | IOError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/views/i18n.py/javascript_catalog |
7,365 | def get_terminal_size(fallback=(80, 24)):
"""Get the size of the terminal window.
For each of the two dimensions, the environment variable, COLUMNS
and LINES respectively, is checked. If the variable is defined and
the value is a positive integer, it is used.
When COLUMNS or LINES is not defined, ... | KeyError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer_cli/packages/shutil_backport.py/get_terminal_size |
7,366 | @classmethod
def validate(cls, job_config):
"""Inherit docs."""
super(ModelDatastoreInputReader, cls).validate(job_config)
params = job_config.input_reader_params
entity_kind = params[cls.ENTITY_KIND_PARAM]
# Fail fast if Model cannot be located.
try:
model_class = util.for_name(entity_k... | ImportError | dataset/ETHPy150Open GoogleCloudPlatform/appengine-mapreduce/python/src/mapreduce/api/map_job/model_datastore_input_reader.py/ModelDatastoreInputReader.validate |
7,367 | def unzip_to_directory_tree(drop_dir, filepath):
hint_rx = re.compile(r'_((?:un)?hinted)/(.+)')
plain_rx = re.compile(r'[^/]+')
zf = zipfile.ZipFile(filepath, 'r')
print 'extracting files from %s to %s' % (filepath, drop_dir)
count = 0
mapped_names = []
unmapped = []
for name in zf.namelist():
# ski... | KeyError | dataset/ETHPy150Open googlei18n/nototools/nototools/grab_mt_download.py/unzip_to_directory_tree |
7,368 | def verify(inputhashes, **kwargs):
"""
Checks if the group specified is present with the exact matching
configuration provided.
"""
failed = []
for group in inputhashes:
name = group['name']
try:
result = grp.getgrnam(name)
if 'gid' in group:
... | KeyError | dataset/ETHPy150Open gosquadron/squadron/squadron/libraries/group/__init__.py/verify |
7,369 | def apply(inputhashes, log):
"""
Adds the group to the system. If the group is currently present, it fails
as we can't yet modify groups.
"""
failed = []
for group in inputhashes:
name = group['name']
try:
result = grp.getgrnam(name)
# Can't modify groups ... | KeyError | dataset/ETHPy150Open gosquadron/squadron/squadron/libraries/group/__init__.py/apply |
7,370 | def confirm_input(user_input):
"""Check user input for yes, no, or an exit signal"""
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except __HOLE__:
u_inp = user_input
# Check for exit signal
if u_inp in ('q', '... | AttributeError | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/confirm_input |
7,371 | def remove_file(filename):
"""Remove a file from disk"""
try:
os.remove(filename)
return True
except (__HOLE__, IOError):
return False | OSError | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/remove_file |
7,372 | def overwrite_file_check(args, filename):
"""If filename exists, overwrite or modify it to be unique"""
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
tr... | KeyboardInterrupt | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/overwrite_file_check |
7,373 | def write_pdf_files(args, infilenames, outfilename):
"""Write PDF file(s) to disk using pdfkit
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output PDF file (str)
"""
# Modifies fil... | OSError | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/write_pdf_files |
7,374 | def write_file(data, outfilename):
"""Write a single file to disk"""
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, __HOLE__) as err... | IOError | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/write_file |
7,375 | def write_part_images(url, raw_html, html, filename):
"""Write image file(s) associated with HTML to disk, substituting filenames
Keywords arguments:
url -- the URL from which the HTML has been extracted from (str)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file c... | IOError | dataset/ETHPy150Open huntrar/scrape/scrape/utils.py/write_part_images |
7,376 | def stop(self, timeout=None):
"""
Stop the producer (async mode). Blocks until async thread completes.
"""
if timeout is not None:
log.warning('timeout argument to stop() is deprecated - '
'it will be removed in future release')
if not self.as... | ValueError | dataset/ETHPy150Open dpkp/kafka-python/kafka/producer/base.py/Producer.stop |
7,377 | @Override(Experiment)
def do_should_finish(self):
message = '@@@'.join(('status', self.shared_secret))
json_response = self._send_message(message)
if not json_response:
return 10
try:
response = int(json_response)
except __HOLE__:
return 1... | ValueError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/experiments/labview_remote_panels.py/LabviewRemotePanels.do_should_finish |
7,378 | def test_search_invalid_query_as_json(self):
args = {
'output_mode': 'json',
'exec_mode': 'normal'
}
try:
self.service.jobs.create('invalid query', **args)
except SyntaxError as pe:
self.fail("Something went wrong with parsing the REST API ... | HTTPError | dataset/ETHPy150Open splunk/splunk-sdk-python/tests/test_job.py/TestJob.test_search_invalid_query_as_json |
7,379 | def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
"""Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+).
Args:
msvs_settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream ... | ValueError | dataset/ETHPy150Open adobe/brackets-shell/gyp/pylib/gyp/MSVSSettings.py/ConvertToMSBuildSettings |
7,380 | def _ValidateSettings(validators, settings, stderr):
"""Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. ... | ValueError | dataset/ETHPy150Open adobe/brackets-shell/gyp/pylib/gyp/MSVSSettings.py/_ValidateSettings |
7,381 | def get_ingress_ip(k8s, service_name):
"""Gets the public IP address of the service that maps to the remote
builder."""
service = k8s.get_service(service_name)
try:
return service['status']['loadBalancer']['ingress'][0]['ip']
except __HOLE__:
raise KubernetesError(
'Serv... | KeyError | dataset/ETHPy150Open jonparrott/noel/noel/noel/builder/remote.py/get_ingress_ip |
7,382 | def is_valid_url(s):
"""Returns `True` if the given string is a valid URL. This calls
Django's `URLValidator()`, but does not raise an exception.
"""
try:
validate_url(s)
return True
except __HOLE__:
return False | ValidationError | dataset/ETHPy150Open lsaffre/lino/lino/core/utils.py/is_valid_url |
7,383 | def is_valid_email(s):
"""Returns `True` if the given string is a valid email. This calls
Django's `validate_email()`, but does not raise an exception.
"""
try:
validate_email(s)
return True
except __HOLE__:
return False | ValidationError | dataset/ETHPy150Open lsaffre/lino/lino/core/utils.py/is_valid_email |
7,384 | def resolve_app(app_label, strict=False):
"""Return the `modules` module of the given `app_label` if it is
installed. Otherwise return either the :term:`dummy module` for
`app_label` if it exists, or `None`.
If the optional second argument `strict` is `True`, raise
ImportError if the app is not in... | ImportError | dataset/ETHPy150Open lsaffre/lino/lino/core/utils.py/resolve_app |
7,385 | def navinfo(qs, elem):
"""Return a dict with navigation information for the given model
instance `elem` within the given queryset. The dictionary
contains the following keys:
:recno: row number (index +1) of elem in qs
:first: pk of the first element in qs (None if qs is empty)
:prev: ... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/core/utils.py/navinfo |
7,386 | def close(self):
"""Close the contacless reader device."""
with self.lock:
if self.dev:
try: self.dev.close()
except __HOLE__: pass
self.dev = None | IOError | dataset/ETHPy150Open javgh/greenaddress-pos-tools/nfc/clf.py/ContactlessFrontend.close |
7,387 | def connect(self, **options):
"""Connect with a contactless target or become connected as a
contactless target. The calling thread is blocked until a
single activation and deactivation has completed or a callback
function supplied as the keyword argument ``terminate``
returned Tr... | IOError | dataset/ETHPy150Open javgh/greenaddress-pos-tools/nfc/clf.py/ContactlessFrontend.connect |
7,388 | def _check_parameters(self):
super(SpectralBiclustering, self)._check_parameters()
legal_methods = ('bistochastic', 'scale', 'log')
if self.method not in legal_methods:
raise ValueError("Unknown method: '{0}'. method must be"
" one of {1}.".format(self.me... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/cluster/bicluster.py/SpectralBiclustering._check_parameters |
7,389 | def _fit(self, X):
n_sv = self.n_components
if self.method == 'bistochastic':
normalized_data = _bistochastic_normalize(X)
n_sv += 1
elif self.method == 'scale':
normalized_data, _, _ = _scale_normalize(X)
n_sv += 1
elif self.method == 'log... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/cluster/bicluster.py/SpectralBiclustering._fit |
7,390 | def entries(self, fileids, **kwargs):
if 'key' in kwargs:
key = kwargs['key']
del kwargs['key']
else:
key = 'lx' # the default key in MDF
entries = []
for marker, contents in self.fields(fileids, **kwargs):
if marker == key:
... | IndexError | dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/toolbox.py/ToolboxCorpusReader.entries |
7,391 | def readheaders(self):
"""Read header lines.
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error)... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPMessage.readheaders |
7,392 | def _read_status(self):
# Initialize with Simple-Response defaults
line = self.fp.readline()
if self.debuglevel > 0:
print "reply:", repr(line)
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPResponse._read_status |
7,393 | def begin(self):
if self.msg is not None:
# we've already started reading the response
return
# read until we get a non-100 response
while True:
version, status, reason = self._read_status()
if status != CONTINUE:
break
... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPResponse.begin |
7,394 | def _read_chunked(self, amt):
assert self.chunked != _UNKNOWN
chunk_left = self.chunk_left
value = ''
# XXX This accumulates chunks by repeated string concatenation,
# which is not efficient as the number or size of chunks gets big.
while True:
if chu... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPResponse._read_chunked |
7,395 | def _set_hostport(self, host, port):
if port is None:
i = host.rfind(':')
j = host.rfind(']') # ipv6 addresses have [...]
if i > j:
try:
port = int(host[i+1:])
except __HOLE__:
raise Inval... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPConnection._set_hostport |
7,396 | def _send_request(self, method, url, body, headers):
# honour explicitly requested Host: and Accept-Encoding headers
header_names = dict.fromkeys([k.lower() for k in headers])
skips = {}
if 'host' in header_names:
skips['skip_host'] = 1
if 'accept-encoding' in h... | TypeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/HTTPConnection._send_request |
7,397 | def test():
"""Test this module.
A hodge podge of tests collected here, because they have too many
external dependencies for the regular test suite.
"""
import sys
import getopt
opts, args = getopt.getopt(sys.argv[1:], 'd')
dl = 0
for o, a in opts:
if o == '-d':... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/httplib.py/test |
7,398 | def plotXY(data,size = (280,640),margin = 25,name = "data",labels=[], skip = [],
showmax = [], bg = None,label_ndigits = [], showmax_digits=[]):
for x,y in data:
if len(x) < 2 or len(y) < 2:
return
n_plots = len(data)
w = float(size[1])
h = size[0]/float(n_plots)
... | ValueError | dataset/ETHPy150Open thearn/webcam-pulse-detector/lib/interface.py/plotXY |
7,399 | def _get_setitem_indexer(self, key):
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
axis = self.obj._get_axis(0)
if isinstance(axis, MultiIndex):
try:
return axis.get_loc(key)
except Exception:
pass
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/indexing.py/_NDFrameIndexer._get_setitem_indexer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.