Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,900 | def _new(self, im):
new = Image()
new.im = im
new.mode = im.mode
new.size = im.size
new.palette = self.palette
if im.mode == "P":
new.palette = ImagePalette.ImagePalette()
try:
new.info = self.info.copy()
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image._new |
4,901 | def convert(self, mode=None, data=None, dither=None,
palette=WEB, colors=256):
"Convert to other pixel format"
if not mode:
# determine default mode
if self.mode == "P":
self.load()
if self.palette:
mode = self.... | ValueError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.convert |
4,902 | def getpalette(self):
"Get palette contents."
self.load()
try:
return map(ord, self.im.getpalette())
except __HOLE__:
return None # no palette
##
# Returns the pixel value at a given position.
#
# @param xy The coordinate, given as (x, y).
#... | ValueError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.getpalette |
4,903 | def putalpha(self, alpha):
"Set alpha layer"
self.load()
if self.readonly:
self._copy()
if self.mode not in ("LA", "RGBA"):
# attempt to promote self to a matching alpha mode
try:
mode = getmodebase(self.mode) + "A"
tr... | AttributeError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.putalpha |
4,904 | def resize(self, size, resample=NEAREST):
"Resize image"
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"):
resample = NEAREST
if resample == ANTIALIAS:
... | AttributeError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.resize |
4,905 | def save(self, fp, format=None, **params):
"Save image to file or stream"
if isStringType(fp):
filename = fp
else:
if hasattr(fp, "name") and isStringType(fp.name):
filename = fp.name
else:
filename = ""
# may mutate s... | KeyError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.save |
4,906 | def thumbnail(self, size, resample=NEAREST):
"Create thumbnail representation (modifies image in place)"
# FIXME: the default resampling filter will be changed
# to ANTIALIAS in future versions
# preserve aspect ratio
x, y = self.size
if x > size[0]: y = max(y * size[0]... | ValueError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/Image.thumbnail |
4,907 | def fromarray(obj, mode=None):
arr = obj.__array_interface__
shape = arr['shape']
ndim = len(shape)
try:
strides = arr['strides']
except __HOLE__:
strides = None
if mode is None:
try:
typekey = (1, 1) + shape[2:], arr['typestr']
mode, rawmode = _fr... | KeyError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/fromarray |
4,908 | def open(fp, mode="r"):
"Open an image file, without loading the raster data"
if mode != "r":
raise ValueError("bad mode")
if isStringType(fp):
import __builtin__
filename = fp
fp = __builtin__.open(fp, "rb")
else:
filename = ""
prefix = fp.read(16)
pr... | TypeError | dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/Image.py/open |
4,909 | def label(self, key):
try:
return self.segments[key]
except __HOLE__:
return key | KeyError | dataset/ETHPy150Open MontmereLimited/django-lean/django_lean/lean_segments/segments.py/BaseSegments.label |
4,910 | def write_version(name):
'''
Removes the previous configuration file, then creates a new one and writes
the name line. This function is intended to be used from states.
If :mod:`syslog_ng.set_config_file
<salt.modules.syslog_ng.set_config_file>`, is called before, this function
will use the set... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/syslog_ng.py/write_version |
4,911 | def get_page(self, url):
"""
Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).
... | HTTPError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/_vendor/distlib/locators.py/SimpleScrapingLocator.get_page |
4,912 | def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for locator in self.locators:
try:
result |= locator.get_distribution_names()
except __HOLE__:
pass
re... | NotImplementedError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/site-packages/pip/_vendor/distlib/locators.py/AggregatingLocator.get_distribution_names |
4,913 | def load_settings(globals):
"""Loads settings from the configuration file into the caller's locals
dict. This is intended to be used from within a Django settings.py to load
dynamic settings like this:
>>> from opus.lib.conf import load_settings
>>> load_settings()
"""
try:
settings... | KeyError | dataset/ETHPy150Open bmbouter/Opus/opus/lib/conf/__init__.py/load_settings |
4,914 | def pack(self, kid='', owner='', **kwargs):
keys = self.keyjar.get_signing_key(jws.alg2keytype(self.sign_alg),
owner=owner, kid=kid)
if not keys:
raise NoSuitableSigningKeys('kid={}'.format(kid))
key = keys[0] # Might be more then one if ... | KeyError | dataset/ETHPy150Open rohe/pyoidc/src/oic/utils/jwt.py/JWT.pack |
4,915 | def _gen_graph(self, modules, title='Dependency Graph'):
"""
Invoke graphviz and generate graph
"""
try:
graph = Digraph(comment=title, strict=True, format='jpeg')
logging.debug('Creating graph ..')
except __HOLE__:
logging.warning('graphviz mo... | TypeError | dataset/ETHPy150Open CiscoDevNet/yang-explorer/server/explorer/utils/dygraph.py/DYGraph._gen_graph |
4,916 | @app.route('/<ip_addr>')
def lookup_ip(ip_addr):
try:
ip = ipaddress.ip_address(ip_addr)
except __HOLE__:
abort(400)
if ip.version == 4:
gi_city = GI_CITY
gi_org = GI_ORG
r = gi_city.record_by_addr(ip.exploded)
org = gi_org.name_by_addr(ip.exploded)
else:
gi_city = GI_CITY_V6
gi_org = GI_ORG_V6
... | ValueError | dataset/ETHPy150Open kz26/balise/main.py/lookup_ip |
4,917 | def is_frozen(G):
"""Return True if graph is frozen.
Parameters
----------
G : graph
A NetworkX graph
See Also
--------
freeze
"""
try:
return G.frozen
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open networkx/networkx/networkx/classes/function.py/is_frozen |
4,918 | def skip(self):
""" Determine whether or not this object should be skipped.
If this model instance is a parent of a single subclassed
instance, skip it. The subclassed instance will create this
parent instance for us.
TODO: Allow the user to force its creation?
... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/dumpscript.py/InstanceCode.skip |
4,919 | def get_many_to_many_lines(self, force=False):
""" Generates lines that define many to many relations for this instance. """
lines = []
for field, rel_items in self.many_to_many_waiting_list.items():
for rel_item in list(rel_items):
try:
pk_name ... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/dumpscript.py/InstanceCode.get_many_to_many_lines |
4,920 | def get_attribute_value(item, field, context, force=False, skip_autofield=True):
""" Gets a string version of the given attribute's value, like repr() might. """
# Find the value of the field, catching any database issues
try:
value = getattr(item, field.name)
except __HOLE__:
raise Ski... | ObjectDoesNotExist | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/dumpscript.py/get_attribute_value |
4,921 | def installed_apps(parser, token):
try:
tag_name, arg = token.contents.split(None, 1)
except __HOLE__:
raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
m = re.search(r'as (\w+)', arg)
if not m:
raise template.TemplateSyntaxError, "%r tag... | ValueError | dataset/ETHPy150Open svetlyak40wt/django-apps/django_apps/templatetags/apps_tags.py/installed_apps |
4,922 | def format_pymux_string(pymux, cli, string, window=None, pane=None):
"""
Apply pymux sting formatting. (Similar to tmux.)
E.g. #P is replaced by the index of the active pane.
We try to stay compatible with tmux, if possible.
One thing that we won't support (for now) is colors, because our styling
... | ValueError | dataset/ETHPy150Open jonathanslenders/pymux/pymux/format.py/format_pymux_string |
4,923 | def _request(self, url, method='GET', params=None, api_call=None):
"""Internal request method"""
method = method.lower()
params = params or {}
func = getattr(self.client, method)
params, files = _transparent_params(params)
requests_args = {}
for k, v in self.cli... | ValueError | dataset/ETHPy150Open splunk/splunk-app-twitter/twitter2/bin/twython/api.py/Twython._request |
4,924 | def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated read-only calls.
:rtype: string
"""
if self.oauth_version != 2:
raise TwythonError('This method can only be called when your OAuth version is 2.0.')
data = {'grant_type':... | AttributeError | dataset/ETHPy150Open splunk/splunk-app-twitter/twitter2/bin/twython/api.py/Twython.obtain_access_token |
4,925 | def search_gen(self, search_query, **params):
"""Returns a generator of tweets that match a specified query.
Documentation: https://dev.twitter.com/docs/api/1.1/get/search/tweets
:param search_query: Query you intend to search Twitter for
:param \*\*params: Extra parameters to send wit... | ValueError | dataset/ETHPy150Open splunk/splunk-app-twitter/twitter2/bin/twython/api.py/Twython.search_gen |
4,926 | @extensionclassmethod(Observable)
def catch_exception(cls, *args):
"""Continues an observable sequence that is terminated by an
exception with the next observable sequence.
1 - res = Observable.catch_exception(xs, ys, zs)
2 - res = Observable.catch_exception([xs, ys, zs])
Returns an observable seq... | StopIteration | dataset/ETHPy150Open ReactiveX/RxPY/rx/linq/observable/catch.py/catch_exception |
4,927 | @requires_version('scipy', '0.11')
def test_add_patch_info():
"""Test adding patch info to source space"""
# let's setup a small source space
src = read_source_spaces(fname_small)
src_new = read_source_spaces(fname_small)
for s in src_new:
s['nearest'] = None
s['nearest_dist'] = None... | RuntimeError | dataset/ETHPy150Open mne-tools/mne-python/mne/tests/test_source_space.py/test_add_patch_info |
4,928 | @testing.requires_testing_data
@requires_version('scipy', '0.11')
def test_add_source_space_distances_limited():
"""Test adding distances to source space with a dist_limit"""
tempdir = _TempDir()
src = read_source_spaces(fname)
src_new = read_source_spaces(fname)
del src_new[0]['dist']
del src_n... | RuntimeError | dataset/ETHPy150Open mne-tools/mne-python/mne/tests/test_source_space.py/test_add_source_space_distances_limited |
4,929 | def reverts(action):
try:
return list(_INVERSES[action])
except __HOLE__:
return [] | KeyError | dataset/ETHPy150Open openstack/anvil/anvil/actions/states.py/reverts |
4,930 | def receiver(self):
buf = bytearray()
sock = self._sock
wait_read = gethub().do_read
add_chunk = buf.extend
pos = [0]
def readmore():
while True:
wait_read(sock)
try:
if pos[0]*2 > len(buf):
... | ValueError | dataset/ETHPy150Open tailhook/zorro/zorro/redis.py/RedisChannel.receiver |
4,931 | def findPanels(self) :
"""
find panels from grabbed websites
the attacker may do a lot of vulnerabilty
tests on the admin area
"""
print "[~] Finding admin panels"
adminList = ['admin/', 'site/admin', 'admin.php/', 'up/admin/', 'central/admin/', 'whm/admin/', 'wh... | IOError | dataset/ETHPy150Open x3omdax/PenBox/Versions/V1.3/penbox.py/TNscan.findPanels |
4,932 | def findZip(self) :
"""
find zip files from grabbed websites
it may contain useful informations
"""
zipList = ['backup.tar.gz', 'backup/backup.tar.gz', 'backup/backup.zip', 'vb/backup.zip', 'site/backup.zip', 'backup.zip', 'backup.rar', 'backup.sql', 'vb/vb.zip', 'vb.zip', 'vb.sq... | IOError | dataset/ETHPy150Open x3omdax/PenBox/Versions/V1.3/penbox.py/TNscan.findZip |
4,933 | def findUp(self) :
"""
find upload forms from grabbed
websites the attacker may succeed to
upload malicious files like webshells
"""
upList = ['up.php', 'up1.php', 'up/up.php', 'site/up.php', 'vb/up.php', 'forum/up.php','blog/up.php', 'upload.php', 'upload1.php', 'uploa... | IOError | dataset/ETHPy150Open x3omdax/PenBox/Versions/V1.3/penbox.py/TNscan.findUp |
4,934 | def ParseRate(rate):
"""Parses a rate string in the form number/unit, or the literal 0.
The unit is one of s (seconds), m (minutes), h (hours) or d (days).
Args:
rate: the rate string.
Returns:
a floating point number representing the rate/second.
Raises:
MalformedQueueConfiguration: if the ra... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/queueinfo.py/ParseRate |
4,935 | def ParseTotalStorageLimit(limit):
"""Parses a string representing the storage bytes limit.
Optional limit suffixes are:
B (bytes), K (kilobytes), M (megabytes), G (gigabytes), T (terabytes)
Args:
limit: The storage bytes limit string.
Returns:
An int representing the storage limit in bytes.
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/queueinfo.py/ParseTotalStorageLimit |
4,936 | def ParseTaskAgeLimit(age_limit):
"""Parses a string representing the task's age limit (maximum allowed age).
The string must be a non-negative integer or floating point number followed by
one of s, m, h, or d (seconds, minutes, hours or days respectively).
Args:
age_limit: The task age limit string.
R... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/queueinfo.py/ParseTaskAgeLimit |
4,937 | def on_request(self, request):
if not self.ssl:
return request
try:
record, remaining = tls.parse_tls(request)
message = record.messages[0]
if not self.clienthello_adjusted:
self.clienthello_adjusted = True
hello = message.o... | ValueError | dataset/ETHPy150Open google/nogotofail/nogotofail/mitm/connection/handlers/connection/serverkeyreplace.py/ServerKeyReplacementMITM.on_request |
4,938 | def update_latest_symlink(outdir, latest_symlink):
"""Updates the 'latest' symlink to point to the given outdir."""
if os.path.lexists(latest_symlink):
try:
os.remove(latest_symlink)
except OSError as err:
return err
try:
os.symlink(os.path.basename(auto_outdir), latest_symlink)
except _... | OSError | dataset/ETHPy150Open m-lab/operator/tools/fetch.py/update_latest_symlink |
4,939 | def log(self, level, message):
logline = self._logline(message)
try:
self.assem_logger.log(level, logline)
except __HOLE__ as e:
LOG.error(e) | IOError | dataset/ETHPy150Open openstack/solum/solum/uploaders/tenant_logger.py/TenantLogger.log |
4,940 | @defer.inlineCallbacks
def action_get_request(self, data):
from .http import Request
try:
reqid = data['reqid']
req = yield Request.load_request(reqid)
except __HOLE__:
raise PappyException("Request with given ID does not exist")
dat = json.loads(... | KeyError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/comm.py/CommServer.action_get_request |
4,941 | @defer.inlineCallbacks
def action_get_response(self, data):
from .http import Request, Response
try:
reqid = data['reqid']
req = yield Request.load_request(reqid)
except __HOLE__:
raise PappyException("Request with given ID does not exist, cannot fetch ass... | KeyError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/comm.py/CommServer.action_get_response |
4,942 | def base64_b64decode(instr):
'''
Decode a base64-encoded string using the "modern" Python interface
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' hashutil.base64_b64decode 'Z2V0IHNhbHRlZA=='
'''
if six.PY3:
b = salt.utils.to_bytes(instr)
da... | UnicodeDecodeError | dataset/ETHPy150Open saltstack/salt/salt/modules/hashutil.py/base64_b64decode |
4,943 | def base64_decodestring(instr):
'''
Decode a base64-encoded string using the "legacy" Python interface
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' hashutil.base64_decodestring instr='Z2V0IHNhbHRlZAo='
'''
if six.PY3:
b = salt.utils.to_bytes(inst... | UnicodeDecodeError | dataset/ETHPy150Open saltstack/salt/salt/modules/hashutil.py/base64_decodestring |
4,944 | def test_push_pop(self):
# 1) Push 256 random numbers and pop them off, verifying all's OK.
heap = []
data = []
self.check_invariant(heap)
for i in range(256):
item = random.random()
data.append(item)
self.module.heappush(heap, item)
... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_heapq.py/TestHeap.test_push_pop |
4,945 | def heapiter(self, heap):
# An iterator returning a heap's elements, smallest-first.
try:
while 1:
yield self.module.heappop(heap)
except __HOLE__:
pass | IndexError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_heapq.py/TestHeap.heapiter |
4,946 | def open(self, url):
try:
content, headers_dict = self.url_mappings[url]
except __HOLE__:
raise IOError # simulate a connection error
if callable(content):
content = content()
if not hasattr(content, 'read'):
f = StringIO(content)
h... | KeyError | dataset/ETHPy150Open ofri/Open-Knesset/mks/mock.py/MockReader.open |
4,947 | def main(restarted=False):
es = ExploitSearch()
if restarted:
es.intro = '\n'
try:
es.cmdloop()
except __HOLE__:
main(True) | KeyboardInterrupt | dataset/ETHPy150Open Gioyik/getExploit/getExploit.py/main |
4,948 | def __iter__(self):
it = iter(self.table)
hdr = next(it)
shdr = sorted(hdr)
indices = asindices(hdr, shdr)
transform = rowgetter(*indices)
# yield the transformed header
yield tuple(shdr)
# construct the transformed data
missing = self.missing
... | IndexError | dataset/ETHPy150Open alimanfoo/petl/petl/transform/headers.py/SortHeaderView.__iter__ |
4,949 | def parse_json_file(filename):
"""open file and parse its content as json"""
with open(filename, 'r') as jsonfile:
content = jsonfile.read()
try:
result = json.loads(content)
except __HOLE__:
_logger.error(
"Parsing file %s failed. Check syntax wit... | ValueError | dataset/ETHPy150Open MA3STR0/kimsufi-crawler/crawler.py/parse_json_file |
4,950 | @coroutine
def run(self):
"""Run a crawler iteration"""
http_client = AsyncHTTPClient()
# request OVH availability API asynchronously
try:
response = yield http_client.fetch(self.API_URL, request_timeout=REQUEST_TIMEOUT)
except __HOLE__ as ex:
# Intern... | HTTPError | dataset/ETHPy150Open MA3STR0/kimsufi-crawler/crawler.py/Crawler.run |
4,951 | def get_git_shas_for_service(service, deploy_groups, soa_dir):
"""Returns a list of 2-tuples of the form (sha, timestamp) for each deploy tag in a service's git
repository"""
if service is None:
return []
git_url = get_git_url(service=service, soa_dir=soa_dir)
all_deploy_groups = {config.get... | KeyError | dataset/ETHPy150Open Yelp/paasta/paasta_tools/cli/cmds/rollback.py/get_git_shas_for_service |
4,952 | def test_impersonation():
from hbased import Hbase as thrift_hbase
c = make_logged_in_client(username='test_hbase', is_superuser=False)
grant_access('test_hbase', 'test_hbase', 'hbase')
user = User.objects.get(username='test_hbase')
proto = MockProtocol()
client = thrift_hbase.Client(proto)
impersonati... | AttributeError | dataset/ETHPy150Open cloudera/hue/apps/hbase/src/hbase/tests.py/test_impersonation |
4,953 | def log_line_parser(self, raw_log):
'''given a raw access log line, return a dict of the good parts'''
d = {}
try:
log_source = None
split_log = raw_log[16:].split(' ')
(unused,
server,
client_ip,
lb_ip,
timestam... | ValueError | dataset/ETHPy150Open notmyname/slogging/slogging/access_processor.py/AccessLogProcessor.log_line_parser |
4,954 | def __getattr__(self, name):
try:
return self.instance.metadata.get(metadata_type__name=name).value
except __HOLE__:
raise AttributeError(
_('\'metadata\' object has no attribute \'%s\'') % name
) | ObjectDoesNotExist | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/metadata/classes.py/DocumentMetadataHelper.__getattr__ |
4,955 | def exception_str(value):
'''
Formats Exception object to a string. Unlike default str():
- can handle unicode strings in exception arguments
- tries to format arguments as str(), not as repr()
'''
try:
return ', '.join([smart_str(b) for b in value])
except (TypeError, __HOLE__): # ... | AttributeError | dataset/ETHPy150Open isagalaev/django_errorlog/django_errorlog/models.py/exception_str |
4,956 | def put_stream(self, bucket, label, stream_object, params={}):
## QUESTION: do we enforce that the bucket's have to be 'claimed' first?
## NB this method doesn't care if it has been
po, json_payload = self._get_object(bucket)
if label in json_payload.keys():
creation_date = ... | TypeError | dataset/ETHPy150Open okfn/ofs/ofs/local/pairtreestore.py/PTOFS.put_stream |
4,957 | @staticmethod
def GetHGRevision():
"""Attempts to retrieve the current mercurial revision number from the local
filesystem.
"""
filename = os.path.join(os.path.dirname(__file__), '../../hg_revision.txt')
try:
with open(filename) as f:
return f.read().strip()
except __HOLE__:
... | IOError | dataset/ETHPy150Open viewfinderco/viewfinder/backend/base/environ.py/ServerEnvironment.GetHGRevision |
4,958 | def _makeDgModGhostObject(mayaType, dagMod, dgMod):
# we create a dummy object of this type in a dgModifier (or dagModifier)
# as the dgModifier.doIt() method is never called, the object
# is never actually created in the scene
# Note: at one point, if we didn't call the dgMod/dagMod.deleteNode method,... | RuntimeError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/apicache.py/_makeDgModGhostObject |
4,959 | def _buildApiClassInfo(self):
_logger.debug("Starting ApiCache._buildApiClassInfo...")
from pymel.internal.parsers import ApiDocParser
self.apiClassInfo = {}
parser = ApiDocParser(api, enumClass=ApiEnum)
for name, obj in inspect.getmembers( api, lambda x: type(x) == type and x.... | ValueError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/internal/apicache.py/ApiCache._buildApiClassInfo |
4,960 | def static_serve(request, path, client):
"""
Given a request for a media asset, this view does the necessary wrangling
to get the correct thing delivered to the user. This can also emulate the
combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
"""
if msettings['SERVE_... | KeyError | dataset/ETHPy150Open sunlightlabs/django-mediasync/mediasync/views.py/static_serve |
4,961 | def rebuild_servers():
"""
The function the rebuilds the set of servers
"""
try:
global Servers
servers = btcnet_info.get_pools().copy()
for filter_f in filters:
servers = filter_f(servers)
Servers = list(servers)
except __HOLE__ as Error:
logging.... | ValueError | dataset/ETHPy150Open c00w/bitHopper/bitHopper/Logic/ServerLogic.py/rebuild_servers |
4,962 | def create_container(image,
command=None,
hostname=None,
user=None,
detach=True,
stdin_open=False,
tty=False,
mem_limit=None,
ports=None,
... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/dockerio.py/create_container |
4,963 | def start(container,
binds=None,
port_bindings=None,
lxc_conf=None,
publish_all_ports=None,
links=None,
privileged=False,
dns=None,
volumes_from=None,
network_mode=None,
restart_policy=None,
cap_add=None,
... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/dockerio.py/start |
4,964 | def get_images(name=None, quiet=False, all=True):
'''
List docker images
name
repository name
quiet
only show image id, Default is ``False``
all
show all images, Default is ``True``
CLI Example:
.. code-block:: bash
salt '*' docker.get_images <name> [qui... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/dockerio.py/get_images |
4,965 | def find_resource(manager, name_or_id):
"""Helper for the _find_* methods."""
# first try to get entity as integer id
try:
if isinstance(name_or_id, int) or name_or_id.isdigit():
return manager.get(int(name_or_id))
except exceptions.NotFound:
pass
# now try to get entity... | ValueError | dataset/ETHPy150Open kwminnick/rackspace-dns-cli/dnsclient/utils.py/find_resource |
4,966 | def command(self, cmd):
""" Run gphoto2 command """
# Test to see if there is a running command already
if self._proc and self._proc.poll():
raise error.InvalidCommand("Command already running")
else:
# Build the command.
run_cmd = [self._gphoto2, '--... | OSError | dataset/ETHPy150Open panoptes/POCS/panoptes/camera/camera.py/AbstractGPhotoCamera.command |
4,967 | def GetDefaultAPIProxy():
try:
runtime = __import__('google.appengine.runtime', globals(), locals(),
['apiproxy'])
return APIProxyStubMap(runtime.apiproxy)
except (__HOLE__, ImportError):
return APIProxyStubMap() | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/apiproxy_stub_map.py/GetDefaultAPIProxy |
4,968 | def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/iptables.py/get_saved_policy |
4,969 | def get_policy(table='filter', chain=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Example:
.. code-block:: bash
salt '*' iptables.get_policy filter INPUT
IPv6:
salt '*' iptables.get_policy filter INPUT family=ipv6
'''
if not ch... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/iptables.py/get_policy |
4,970 | def messagize(self, pkt, ha):
"""
Returns duple of (message, remote) converted from packet pkt and ha
Override in subclass
"""
msg = pkt.packed.decode("ascii")
try:
remote = self.haRemotes[ha]
except __HOLE__ as ex:
console.concise(("{0}: D... | KeyError | dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/proto/stacking.py/UdpStack.messagize |
4,971 | def _load_config():
try:
with open('config.json') as config_file:
return json.load(config_file)
except __HOLE__:
print('Please check your config.json file!')
return {} | IOError | dataset/ETHPy150Open Alephbet/gimel/config.py/_load_config |
4,972 | def same_origin(url1, url2):
"""
Checks if two URLs are 'same-origin'
"""
PROTOCOL_TO_PORT = {
'http': 80,
'https': 443,
}
p1, p2 = urlparse(url1), urlparse(url2)
try:
o1 = (p1.scheme, p1.hostname, p1.port or PROTOCOL_TO_PORT[p1.scheme])
o2 = (p2.scheme, p2.ho... | KeyError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/same_origin |
4,973 | def is_authenticated(self, request, **kwargs):
"""
Checks a user's basic auth credentials against the current
Django auth backend.
Should return either ``True`` if allowed, ``False`` if not or an
``HttpResponse`` if you need something custom.
"""
try:
... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/BasicAuthentication.is_authenticated |
4,974 | def get_identifier(self, request):
"""
Provides a unique string identifier for the requestor.
This implementation returns the user's basic auth username.
"""
try:
username = self.extract_credentials(request)[0]
except __HOLE__:
username = ''
... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/BasicAuthentication.get_identifier |
4,975 | def extract_credentials(self, request):
try:
data = self.get_authorization_data(request)
except __HOLE__:
username = request.GET.get('username') or request.POST.get('username')
api_key = request.GET.get('api_key') or request.POST.get('api_key')
else:
... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/ApiKeyAuthentication.extract_credentials |
4,976 | def is_authenticated(self, request, **kwargs):
"""
Finds the user and checks their API key.
Should return either ``True`` if allowed, ``False`` if not or an
``HttpResponse`` if you need something custom.
"""
try:
username, api_key = self.extract_credentials(r... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/ApiKeyAuthentication.is_authenticated |
4,977 | def get_identifier(self, request):
"""
Provides a unique string identifier for the requestor.
This implementation returns the user's username.
"""
try:
username = self.extract_credentials(request)[0]
except __HOLE__:
username = ''
return u... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/ApiKeyAuthentication.get_identifier |
4,978 | def is_authenticated(self, request, **kwargs):
"""
Finds the user and checks their API key.
Should return either ``True`` if allowed, ``False`` if not or an
``HttpResponse`` if you need something custom.
"""
try:
self.get_authorization_data(request)
e... | ValueError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/DigestAuthentication.is_authenticated |
4,979 | def get_identifier(self, request):
"""
Provides a unique string identifier for the requestor.
This implementation returns a combination of IP address and hostname.
"""
try:
return request._authentication_backend.get_identifier(request)
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open django-tastypie/django-tastypie/tastypie/authentication.py/MultiAuthentication.get_identifier |
4,980 | def _DetermineFormat(self):
"""Determines whether the feed is in a form that we understand, and
if so, returns True."""
if self._zip:
# If zip was passed to __init__ then path isn't used
assert not self._path
return True
if not isinstance(self._path, basestring) and hasattr(self._p... | IOError | dataset/ETHPy150Open google/transitfeed/transitfeed/loader.py/Loader._DetermineFormat |
4,981 | def _ReadCsvDict(self, file_name, cols, required, deprecated):
"""Reads lines from file_name, yielding a dict of unicode values."""
assert file_name.endswith(".txt")
table_name = file_name[0:-4]
contents = self._GetUtf8Contents(file_name)
if not contents:
return
eol_checker = util.EndOfLi... | IndexError | dataset/ETHPy150Open google/transitfeed/transitfeed/loader.py/Loader._ReadCsvDict |
4,982 | def _ReadCSV(self, file_name, cols, required, deprecated):
"""Reads lines from file_name, yielding a list of unicode values
corresponding to the column names in cols."""
contents = self._GetUtf8Contents(file_name)
if not contents:
return
eol_checker = util.EndOfLineChecker(StringIO.StringIO(c... | UnicodeDecodeError | dataset/ETHPy150Open google/transitfeed/transitfeed/loader.py/Loader._ReadCSV |
4,983 | def _FileContents(self, file_name):
results = None
if self._zip:
try:
results = self._zip.read(file_name)
except KeyError: # file not found in archve
self._problems.MissingFile(file_name)
return None
else:
try:
data_file = open(os.path.join(self._path, file... | IOError | dataset/ETHPy150Open google/transitfeed/transitfeed/loader.py/Loader._FileContents |
4,984 | def _LoadStopTimes(self):
stop_time_class = self._gtfs_factory.StopTime
for (row, row_num, cols) in self._ReadCSV('stop_times.txt',
stop_time_class._FIELD_NAMES,
stop_time_class._REQUIRED_FIELD_NAMES,
stop_time_class._DEPRECATED_FIELD_NAMES):
file_context = ('stop_times.txt', row_... | TypeError | dataset/ETHPy150Open google/transitfeed/transitfeed/loader.py/Loader._LoadStopTimes |
4,985 | def get(self, request, **kwargs):
params = self.get_params(request)
# Get the request's view and context
view = self.get_view(request)
context = self.get_context(request)
# Configure the query options used for retrieving the results.
query_options = {
'expor... | ValueError | dataset/ETHPy150Open chop-dbhi/serrano/serrano/resources/preview.py/PreviewResource.get |
4,986 | def _mkdir_p(path):
"""mkdir -p path"""
try:
os.makedirs(path)
except __HOLE__ as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
else:
logger.info("New: %s%s", path, os.path.sep) | OSError | dataset/ETHPy150Open hustlzp/Flask-Boost/flask_boost/cli.py/_mkdir_p |
4,987 | @test.raises(TypeError)
def test_render_bad_out(self):
self.app.setup()
self.app.run()
try:
self.app.render(dict(foo='bar'), out='bogus type')
except __HOLE__ as e:
self.eq(e.args[0], "Argument 'out' must be a 'file' like object")
raise | TypeError | dataset/ETHPy150Open datafolklabs/cement/tests/core/foundation_tests.py/FoundationTestCase.test_render_bad_out |
4,988 | def test_none_member(self):
class Test(object):
var = None
self.app.setup()
self.app.args.parsed_args = Test()
try:
self.app._parse_args()
except __HOLE__:
pass | SystemExit | dataset/ETHPy150Open datafolklabs/cement/tests/core/foundation_tests.py/FoundationTestCase.test_none_member |
4,989 | @test.raises(SystemExit)
def test_close_with_code(self):
app = self.make_app(APP, exit_on_close=True)
app.setup()
app.run()
try:
app.close(114)
except __HOLE__ as e:
self.eq(e.code, 114)
raise | SystemExit | dataset/ETHPy150Open datafolklabs/cement/tests/core/foundation_tests.py/FoundationTestCase.test_close_with_code |
4,990 | @test.raises(AssertionError)
def test_close_with_bad_code(self):
self.app.setup()
self.app.run()
try:
self.app.close('Not An Int')
except __HOLE__ as e:
self.eq(e.args[0], "Invalid exit status code (must be integer)")
raise | AssertionError | dataset/ETHPy150Open datafolklabs/cement/tests/core/foundation_tests.py/FoundationTestCase.test_close_with_bad_code |
4,991 | @test.raises(AssertionError)
def test_run_forever(self):
class Controller(CementBaseController):
class Meta:
label = 'base'
@expose()
def runit(self):
raise Exception("Fake some error")
app = self.make_app(base_controller=Controll... | AssertionError | dataset/ETHPy150Open datafolklabs/cement/tests/core/foundation_tests.py/FoundationTestCase.test_run_forever |
4,992 | def messageReceived(self, message):
try:
msgtype, topic, payload = self._messageSplit(message)
except __HOLE__:
log.msg('invalid message received <%s>' % message)
return
if topic not in self.channels:
return
if topic in self.endpoints:
... | ValueError | dataset/ETHPy150Open flaviogrossi/sockjs-cyclone/sockjs/cyclone/conn.py/MultiplexConnection.messageReceived |
4,993 | def handleResponse(self, response_body_bytes):
try:
json_response = json.loads(response_body_bytes)
except __HOLE__:
# logger.info("Invalid JSON response from %s",
# self.transport.getHost())
self.transport.abortConnection()
return
... | ValueError | dataset/ETHPy150Open matrix-org/synapse/synapse/crypto/keyclient.py/SynapseKeyClientProtocol.handleResponse |
4,994 | def is_volume_pro_available():
"""Returns `True` if there is a volume pro card available.
"""
try:
map = tvtk.VolumeProMapper()
except __HOLE__:
return False
else:
return map.number_of_boards > 0 | AttributeError | dataset/ETHPy150Open enthought/mayavi/mayavi/modules/volume.py/is_volume_pro_available |
4,995 | def find_volume_mappers():
res = []
for name in dir(tvtk):
if 'Volume' in name and 'Mapper' in name and 'OpenGL' not in name:
try:
klass = getattr(tvtk, name)
inst = klass()
except __HOLE__:
pass
else:
re... | TypeError | dataset/ETHPy150Open enthought/mayavi/mayavi/modules/volume.py/find_volume_mappers |
4,996 | def size_filter(image_url):
try:
file = urlopen(image_url)
except __HOLE__:
return None
data = file.read(1024)
file.close()
parser = ImageParser()
parser.feed(data)
if parser.image:
if parser.image.size[0] > MIN_LINK_THUMB_WIDTH and \
parser.image.size[1] ... | HTTPError | dataset/ETHPy150Open linkfloyd/linkfloyd/linkfloyd/experimental/imgparsing/parser.py/size_filter |
4,997 | def QuerySetMock(model, *return_value):
"""
Get a SharedMock that returns self for most attributes and a new copy of
itself for any method that ordinarily generates QuerySets.
Set the results to two items:
>>> class Post(object): pass
>>> objects = QuerySetMock(Post, 'return', 'values')
>>... | IndexError | dataset/ETHPy150Open dcramer/mock-django/mock_django/query.py/QuerySetMock |
4,998 | def process_request(self, req, resp):
if req.content_length in (None, 0):
# Nothing to do
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['doc'] = json.loads(body.decode('utf-8'))
except (_... | ValueError | dataset/ETHPy150Open mikelynn2/sentimentAPI/sentimentAPI.py/JSONTranslator.process_request |
4,999 | def identify(self, environ):
logger = environ.get('repoze.who.logger','')
logger.info("formplugin identify")
#logger and logger.info("environ keys: %s" % environ.keys())
query = parse_dict_querystring(environ)
# If the extractor finds a special query string on any request,
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/s2repoze/plugins/formswithhidden.py/FormHiddenPlugin.identify |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.