Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
700
def read_request_line(self): # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), ...
ValueError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPRequest.read_request_line
701
def read_request_headers(self): """Read self.rfile into self.inheaders. Return success.""" # then all the http headers try: read_headers(self.rfile, self.inheaders) except __HOLE__: ex = sys.exc_info()[1] self.simple_response("400 Bad Request", ex.arg...
ValueError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPRequest.read_request_headers
702
def unquote_bytes(self, path): """takes quoted string and unquotes % encoded values""" res = path.split(b'%') for i in range(1, len(res)): item = res[i] try: res[i] = bytes([int(item[:2], 16)]) + item[2:] except __HOLE__: raise...
ValueError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPRequest.unquote_bytes
703
def communicate(self): """Read each request and respond appropriately.""" request_seen = False try: while True: # (re)set req to None so that if something goes wrong in # the RequestHandlerClass constructor, the error doesn't # get writ...
SystemExit
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPConnection.communicate
704
def run(self): self.server.stats['Worker Threads'][self.getName()] = self.stats try: self.ready = True while True: conn = self.server.requests.get() if conn is _SHUTDOWNREQUEST: return self.conn = conn ...
KeyboardInterrupt
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/WorkerThread.run
705
def stop(self, timeout=5): # OmniMarkupPreviewer: Force shutdown without waiting too much while self._get_qsize() > 0: conn = self.get() if conn is not _SHUTDOWNREQUEST: conn.close() # Must shut down threads here so the code that calls # this metho...
KeyboardInterrupt
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/ThreadPool.stop
706
def start(self): """Run the server forever.""" # We don't have to trap KeyboardInterrupt or SystemExit here, # because cherrpy.server already does so, calling self.stop() for us. # If you're using this server with another framework, you should # trap those exceptions in whatever ...
SystemExit
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPServer.start
707
def bind(self, family, type, proto=0): """Create (or recreate) the actual socket object.""" self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.nodelay and not isinstanc...
AttributeError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/HTTPServer.bind
708
def get_ssl_adapter_class(name='builtin'): """Return an SSL adapter class for the given name.""" adapter = ssl_adapters[name.lower()] if isinstance(adapter, basestring): last_dot = adapter.rfind(".") attr_name = adapter[last_dot + 1:] mod_path = adapter[:last_dot] try: ...
KeyError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/get_ssl_adapter_class
709
def get_environ(self): """Return a new environ dict targeting the given wsgi.version""" req = self.req env_10 = WSGIGateway_10.get_environ(self) env = env_10.copy() env['wsgi.version'] = ('u', 0) # Request-URI env.setdefault('wsgi.url_encoding', 'utf-8') ...
UnicodeDecodeError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/WSGIGateway_u0.get_environ
710
def __init__(self, apps): try: apps = list(apps.items()) except __HOLE__: pass # Sort the apps by len(path), descending apps.sort() apps.reverse() # The path_prefix strings must start, but not end, with a slash. # Use "" instead of "/". ...
AttributeError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver3.py/WSGIPathInfoDispatcher.__init__
711
def initialize(self, import_func=__import__): """Attempt to import the config module, if not already imported. This function always sets self._module to a value unequal to None: either the imported module (if imported successfully), or a dummy object() instance (if an ImportError was raised). Other ...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/lib_config.py/LibConfigRegistry.initialize
712
def _clear_cache(self): """Clear the cached values.""" self._lock.acquire() try: self._initialized = False for key in self._defaults: self._overrides.pop(key, None) try: delattr(self, key) except __HOLE__: pass finally: self._lock.release()
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/lib_config.py/ConfigHandle._clear_cache
713
def activate_stubs(self, connection): try: from google.appengine.tools import dev_appserver_main self.setup_local_stubs(connection) except __HOLE__: self.activate_test_stubs(connection)
ImportError
dataset/ETHPy150Open django-nonrel/djangoappengine/djangoappengine/db/stubs.py/StubManager.activate_stubs
714
def setup_local_stubs(self, connection): if self.active_stubs == 'local': return from .base import get_datastore_paths from google.appengine.tools import dev_appserver_main args = dev_appserver_main.DEFAULT_ARGS.copy() args.update(get_datastore_paths(connection.setti...
ImportError
dataset/ETHPy150Open django-nonrel/djangoappengine/djangoappengine/db/stubs.py/StubManager.setup_local_stubs
715
def setup_remote_stubs(self, connection): if self.active_stubs == 'remote': return if not connection.remote_api_path: from djangoappengine.utils import appconfig from google.appengine.api import appinfo default_module = next(m for m in appconfig.modules if...
HTTPError
dataset/ETHPy150Open django-nonrel/djangoappengine/djangoappengine/db/stubs.py/StubManager.setup_remote_stubs
716
def runfastcgi(WSGIHandler, argset=[], **kwargs): options = FASTCGI_OPTIONS.copy() options.update(kwargs) for x in argset: if "=" in x: k, v = x.split('=', 1) else: k, v = x, True options[k.lower()] = v if "help" in options: return fastcgi_help() ...
ImportError
dataset/ETHPy150Open mimecuvalo/helloworld/tools/fastcgi.py/runfastcgi
717
def get_result(self, key, date_range=None, reduce=True, verbose_results=False): """ If your Calculator does not have a window set, you must pass a tuple of date or datetime objects to date_range """ if verbose_results: assert not reduce, "can't have reduce set for ver...
IndexError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/fluff/calculators.py/Calculator.get_result
718
def validate_number(self, number): """ Validates the given 1-based page number. """ try: number = int(number) except (TypeError, __HOLE__): raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('Tha...
ValueError
dataset/ETHPy150Open django/django/django/core/paginator.py/Paginator.validate_number
719
@cached_property def count(self): """ Returns the total number of objects, across all pages. """ try: return self.object_list.count() except (__HOLE__, TypeError): # AttributeError if object_list has no count() method. # TypeError if object...
AttributeError
dataset/ETHPy150Open django/django/django/core/paginator.py/Paginator.count
720
def load_tool_info(tool_name): """ Load the tool-info class. @param tool_name: The name of the tool-info module. Either a full Python package name or a name within the benchexec.tools package. @return: A tuple of the full name of the used tool-info module and an instance of the tool-info class. ...
AttributeError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/model.py/load_tool_info
721
def __init__(self, benchmark_file, config, start_time): """ The constructor of Benchmark reads the source files, options, columns and the tool from the XML in the benchmark_file.. """ logging.debug("I'm loading the benchmark %s.", benchmark_file) self.config = config ...
ValueError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/model.py/Benchmark.__init__
722
def after_execution(self, exitcode, forceTimeout=False, termination_reason=None): """ @deprecated: use set_result() instead """ # termination reason is not fully precise for timeouts, so we guess "timeouts" # if time is too high isTimeout = forceTimeout \ ...
IOError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/model.py/Run.after_execution
723
def __init__(self, tags, rlimits, config): self.cpu_model = None self.memory = None self.cpu_cores = None for requireTag in tags: cpu_model = requireTag.get('cpuModel', None) if cpu_model: if self.cpu_model is None: self.cp...
ValueError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/model.py/Requirements.__init__
724
def is_num_list(item): try: for thing in item: if not isinstance(thing, Num): raise TypeError except __HOLE__: return False return True
TypeError
dataset/ETHPy150Open plotly/plotly.py/plotly/tests/utils.py/is_num_list
725
def _add_handler(self): try: handler = RotatingFileHandler( '/var/log/%s.log' % self.log_name, maxBytes=10485760, backupCount=3 ) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ...
IOError
dataset/ETHPy150Open bcoe/smtproutes/smtproutes/config/log.py/Log._add_handler
726
def get_history(self): try: n = readline.get_current_history_length() except __HOLE__: return [] return [readline.get_history_item(i) for i in range(1, n + 1)]
NameError
dataset/ETHPy150Open njr0/fish/fish/fish.py/REPL.get_history
727
def _supports_stddev(self): "Confirm support for STDDEV and related stats functions" class StdDevPop(object): sql_function = 'STDDEV_POP' try: self.connection.ops.check_aggregate_support(StdDevPop()) except __HOLE__: self.supports_stddev = False
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/db/backends/__init__.py/BaseDatabaseFeatures._supports_stddev
728
def lazy_imports(*args): query = ' '.join([x for x in args if x]) regex = re.compile("([a-zA-Z_][a-zA-Z0-9_]*)\.?") matches = regex.findall(query) for raw_module_name in matches: if re.match('np(\..*)?$', raw_module_name): module_name = re.sub('^np', 'numpy', raw_module_name) ...
ImportError
dataset/ETHPy150Open Russell91/pythonpy/pythonpy/pycompleter.py/lazy_imports
729
def get_completerlib(): """Implementations for various useful completers. These are all loaded by default by IPython. """ #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team. # # Distributed under the terms ...
ImportError
dataset/ETHPy150Open Russell91/pythonpy/pythonpy/pycompleter.py/get_completerlib
730
def render_option(self, name, selected_choices, option_value, option_label): option_value = force_text(option_value) if option_label == BLANK_CHOICE_DASH[0][1]: option_label = _("All") data = self.data.copy() data[name] = option_value selected = ...
AttributeError
dataset/ETHPy150Open carltongibson/django-filter/django_filters/widgets.py/LinkWidget.render_option
731
def render(self, name, value, attrs=None): try: value = { True: 'true', False: 'false', '1': 'true', '0': 'false' }[value] except __HOLE__: value = '' return super(BooleanWidget, self).render(name...
KeyError
dataset/ETHPy150Open carltongibson/django-filter/django_filters/widgets.py/BooleanWidget.render
732
def json_decode_hook(data): for key, value in list(data.items()): if not isinstance(value, six.string_types): continue for regex, fns in _PATTERNS: if regex.match(value): for fn in fns: try: data[key] = fn(value) ...
ValueError
dataset/ETHPy150Open matthiask/plata/plata/fields.py/json_decode_hook
733
def clean(self, value, *args, **kwargs): if value: try: # Run the value through JSON so we can normalize formatting # and at least learn about malformed data: value = json.dumps( json.loads( value, ...
ValueError
dataset/ETHPy150Open matthiask/plata/plata/fields.py/JSONFormField.clean
734
def to_python(self, value): """Convert our string value to JSON after we load it from the DB""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): # Avoid asking the JSON decoder to handle empty values: if not value: ...
ValueError
dataset/ETHPy150Open matthiask/plata/plata/fields.py/JSONField.to_python
735
def unpack(self, buf): dpkt.Packet.unpack(self, buf) n = self.len - 4 if n > len(self.data): raise dpkt.NeedData('not enough data') self.msg, self.data = self.data[:n], self.data[n:] try: p = self._msgsw[self.msgid](self.msg) setattr(self, p.__...
KeyError
dataset/ETHPy150Open dragondjf/QMarkdowner/dpkt/sccp.py/SCCP.unpack
736
def parse(self, *args, **kwargs): text = get_text(self.view) try: text = strip_js_comments(text) data = json.loads(text) except __HOLE__ as e: self.output.write_line(self.debug_base % (self.file_path, str(e))) else: return data
ValueError
dataset/ETHPy150Open SublimeText/PackageDev/fileconv/loaders.py/JSONLoader.parse
737
def parse(self, *args, **kwargs): text = get_text(self.view) try: data = yaml.safe_load(text) except yaml.YAMLError as e: out = self.debug_base % str(e).replace("<unicode string>", self.file_path) self.output.write_line(out) except __HOLE__ as e: ...
IOError
dataset/ETHPy150Open SublimeText/PackageDev/fileconv/loaders.py/YAMLLoader.parse
738
def _setup_dir(self, base_dir): """ Creates stats directory for storing stat files. `base_dir` Base directory. """ stats_dir = self._sdir(base_dir) if not os.path.isdir(stats_dir): try: os.mkdir(stats_dir) except _...
OSError
dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/stats.py/Stats._setup_dir
739
def _log_task(self, task): """ Logs task record to file. `task` ``Task`` instance. """ if not task.duration: return self._setup_dir(task.base_dir) stats_dir = self._sdir(task.base_dir) duration = task.duration while d...
ValueError
dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/stats.py/Stats._log_task
740
def _get_stats(self, task, start_date): """ Fetches statistic information for given task and start range. """ stats = [] stats_dir = self._sdir(task.base_dir) date = start_date end_date = datetime.date.today() delta = datetime.timedelta(days=1) while...
OSError
dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/stats.py/Stats._get_stats
741
def parse_script_name(self, name): if name is None: return (None, None) try: lang, script_id = name.split("/") except __HOLE__: return (None, None) return (lang, script_id)
ValueError
dataset/ETHPy150Open KunihikoKido/sublime-elasticsearch-client/commands/put_script.py/PutScriptCommand.parse_script_name
742
def update(self, row, keys, ensure=None, types={}): """ Update a row in the table. The update is managed via the set of column names stated in ``keys``: they will be used as filters for the data to be updated, using the values in ``row``. :: # update all ent...
KeyError
dataset/ETHPy150Open pudo/dataset/dataset/persistence/table.py/Table.update
743
def upsert(self, row, keys, ensure=None, types={}): """ An UPSERT is a smart combination of insert and update. If rows with matching ``keys`` exist they will be updated, otherwise a new row is inserted in the table. :: data = dict(id=10, title='I am a banana!') ...
KeyError
dataset/ETHPy150Open pudo/dataset/dataset/persistence/table.py/Table.upsert
744
def find_one(self, *args, **kwargs): """ Get a single result from the table. Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: row = table.find_one(country='United States') """ kwargs['_limit'] = 1 iterator =...
StopIteration
dataset/ETHPy150Open pudo/dataset/dataset/persistence/table.py/Table.find_one
745
def distinct(self, *args, **_filter): """ Return all rows of a table, but remove rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring the re...
KeyError
dataset/ETHPy150Open pudo/dataset/dataset/persistence/table.py/Table.distinct
746
def ensure_tree(path): """Create a directory (and any ancestor directories required) :param path: Directory to create """ try: os.makedirs(path) except __HOLE__ as exc: if exc.errno == errno.EEXIST: if not os.path.isdir(path): raise else: ...
OSError
dataset/ETHPy150Open openstack/solum/solum/openstack/common/fileutils.py/ensure_tree
747
def delete_if_exists(path, remove=os.unlink): """Delete a file, but ignore file not found error. :param path: File to delete :param remove: Optional function to remove passed path """ try: remove(path) except __HOLE__ as e: if e.errno != errno.ENOENT: raise
OSError
dataset/ETHPy150Open openstack/solum/solum/openstack/common/fileutils.py/delete_if_exists
748
def _scoreLoadRecipeChoice(labelPath, version): # FIXME I'm quite sure this heuristic will get replaced with # something smarter/more sane as time progresses if not labelPath: return 0 score = 0 labelPath = [ x for x in reversed(labelPath)] branch = version.branch() while True: ...
ValueError
dataset/ETHPy150Open sassoftware/conary/conary/build/loadrecipe.py/_scoreLoadRecipeChoice
749
@classmethod def get_identifier(cls, obj): identifier = super(BootstrapPicturePlugin, cls).get_identifier(obj) try: content = force_text(obj.image) except __HOLE__: content = _("No Picture") return format_html('{0}{1}', identifier, content)
AttributeError
dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/bootstrap3/picture.py/BootstrapPicturePlugin.get_identifier
750
def unregister_image_format(format_name): global FORMATS # handle being passed a format object rather than a format name string try: format_name = format_name.name except __HOLE__: pass try: del FORMATS_BY_NAME[format_name] FORMATS = [fmt for fmt in FORMATS if fmt.na...
AttributeError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailimages/formats.py/unregister_image_format
751
def capture_payment(self, testing=False, order=None, amount=None): """ Creates and sends XML representation of transaction to Cybersource """ if not order: order = self.order if order.paid_in_full: self.log_extra('%s is paid in full, no capture attempted....
KeyError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/payment/modules/cybersource/processor.py/PaymentProcessor.capture_payment
752
def is_fits(filename): from astropy.io import fits try: with warnings.catch_warnings(): warnings.simplefilter("ignore") with fits.open(filename, ignore_missing_end=True): return True except __HOLE__: return False
IOError
dataset/ETHPy150Open glue-viz/glue/glue/core/data_factories/fits.py/is_fits
753
@data_factory( label='FITS file', identifier=is_fits, priority=100, ) def fits_reader(source, auto_merge=False, exclude_exts=None, label=None): """ Read in all extensions from a FITS file. Parameters ---------- source: str or HDUList The pathname to the FITS file. If an ...
KeyError
dataset/ETHPy150Open glue-viz/glue/glue/core/data_factories/fits.py/fits_reader
754
def prep_jid(nocache=False, passed_jid=None, recurse_count=0): ''' Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case ''' if recurse_cou...
OSError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/prep_jid
755
def returner(load): ''' Return data to the local job cache ''' serial = salt.payload.Serial(__opts__) # if a minion is returning a standalone job, get a jobid if load['jid'] == 'req': load['jid'] = prep_jid(nocache=load.get('nocache', False)) jid_dir = _jid_dir(load['jid']) if ...
OSError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/returner
756
def save_load(jid, clear_load, minions=None, recurse_count=0): ''' Save the load to the specified jid minions argument is to provide a pre-computed list of matched minions for the job, for cases when this function can't compute that list itself (such as for salt-ssh) ''' if recurse_count >=...
OSError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/save_load
757
def save_minions(jid, minions, syndic_id=None): ''' Save/update the serialized list of minions for a given job ''' log.debug( 'Adding minions for job %s%s: %s', jid, ' from syndic master \'{0}\''.format(syndic_id) if syndic_id else '', minions ) serial = salt.payl...
IOError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/save_minions
758
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid_dir = _jid_dir(jid) load_fn = os.path.join(jid_dir, LOAD_P) if not os.path.exists(jid_dir) or not os.path.exists(load_fn): return {} serial = salt.payload.Serial(__opts__) ret = serial.load(salt.utils...
IOError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/get_load
759
def update_endtime(jid, time): ''' Update (or store) the end time for a given job Endtime is stored as a plain text string ''' jid_dir = _jid_dir(jid) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) with salt.utils.fopen(os.path.join(jid_dir, ENDTIME), 'w')...
IOError
dataset/ETHPy150Open saltstack/salt/salt/returners/local_cache.py/update_endtime
760
def split_fd(self, fd): """Returns an (fd, obj) pair from an ``fd`` parameter. We accept both raw file descriptors and file-like objects as input to `add_handler` and related methods. When a file-like object is passed, we must retain the object itself so we can close it correct...
AttributeError
dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/ioloop.py/IOLoop.split_fd
761
def close_fd(self, fd): """Utility method to close an ``fd``. If ``fd`` is a file-like object, we close it directly; otherwise we use `os.close`. This method is provided for use by `IOLoop` subclasses (in implementations of ``IOLoop.close(all_fds=True)`` and should not ...
AttributeError
dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/ioloop.py/IOLoop.close_fd
762
def start(self): if self._running: raise RuntimeError("IOLoop is already running") self._setup_logging() if self._stopped: self._stopped = False return old_current = getattr(IOLoop._current, "instance", None) IOLoop._current.instance = self ...
IOError
dataset/ETHPy150Open RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/ioloop.py/PollIOLoop.start
763
def show_state(*arguments): """Shows the contents of the state loaded by the configuration or from the file specified as an argument. """ if len(arguments) == 0: state_file = conf['pyexperiment.state_filename'] else: state_file = arguments[0] print_bold("Load state from file '%s'...
IOError
dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/experiment.py/show_state
764
@classmethod def RemoveInstance(cls, name): """Removes load information entry of the instance. Args: name: Name of the instance to remove from load information list. """ # Use cas operation to remove from instance name list. memcache_client = memcache.Client() while True: instance...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/solutions-load-balanced-gaming-server-on-google-compute-engine/load_info.py/LoadInfo.RemoveInstance
765
def previous_current_next(items): """ From http://www.wordaligned.org/articles/zippy-triples-served-with-python Creates an iterator which returns (previous, current, next) triples, with ``None`` filling in when there is no previous or next available. """ extend = itertools.chain([No...
StopIteration
dataset/ETHPy150Open fabiocorneti/django-easytree/easytree/templatetags/easytree_tags.py/previous_current_next
766
def matches_requirement(req, wheels): """List of wheels matching a requirement. :param req: The requirement to satisfy :param wheels: List of wheels to search. """ try: from pkg_resources import Distribution, Requirement except __HOLE__: raise RuntimeError("Cannot use requiremen...
ImportError
dataset/ETHPy150Open chalasr/Flask-P2P/venv/lib/python2.7/site-packages/wheel/util.py/matches_requirement
767
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): """ Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: ...
KeyboardInterrupt
dataset/ETHPy150Open SheffieldML/GPy/GPy/core/gp.py/GP.optimize
768
def lazy_property(undecorated): name = '_' + undecorated.__name__ @property @wraps(undecorated) def decorated(self): try: return getattr(self, name) except __HOLE__: v = undecorated(self) setattr(self, name, v) return v return decorated
AttributeError
dataset/ETHPy150Open samuel/kokki/kokki/system.py/lazy_property
769
@classmethod def get_instance(cls): try: return cls._instance except __HOLE__: cls._instance = cls() return cls._instance
AttributeError
dataset/ETHPy150Open samuel/kokki/kokki/system.py/System.get_instance
770
def get_cinspect_object(obj): """ Returns the object wrapped in the appropriate CInspectObject class. """ try: with inspect_restored(): inspect.getsource(obj) except (TypeError, __HOLE__): wrapped = _get_cinspect_object(obj) else: wrapped = PythonObject(obj) r...
IOError
dataset/ETHPy150Open punchagan/cinspect/cinspect/_types.py/get_cinspect_object
771
@register.filter(name="markdown") def markdown(value, arg=''): try: from niwi.contrib.markdown2 import markdown except __HOLE__: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.") return force_...
ImportError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/web/templatetags/utils.py/markdown
772
@register.tag(name="show_page") def show_page(parser, token): """ Render litle block obtaingin source from dinamicaly writed on Page model. """ try: tag_name, page_name = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError("%r tag requires a single argume...
ValueError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/web/templatetags/utils.py/show_page
773
@register.tag(name="render_page_as_template") def render_tmpl(parser, token): """ Renders model objects content as template. """ try: tag_name, obj = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError("%r tag requires a single argument" % \ ...
ValueError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/web/templatetags/utils.py/render_tmpl
774
@register.tag(name='post_file_link') def post_file_link(parser, token): try: tag_name, slug = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError("%r tag requires a single argument" % \ token.contents.split()[0]) slug = parser.c...
ValueError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/web/templatetags/utils.py/post_file_link
775
@register.tag(name='post_file_url') def post_file_url(parser, token): try: tag_name, slug = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError("%r tag requires a single argument" % \ token.contents.split()[0]) slug = parser.com...
ValueError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/web/templatetags/utils.py/post_file_url
776
def elem_to_internal(elem, strip_ns=1, strip=1): """Convert an Element into an internal dictionary (not JSON!).""" d = {} elem_tag = elem.tag if strip_ns: elem_tag = strip_tag(elem.tag) else: for key, value in list(elem.attrib.items()): d['@' + key] = value # loop o...
AttributeError
dataset/ETHPy150Open hay/xml2json/xml2json.py/elem_to_internal
777
def panset(self, fitsimage, channel, paninfo): image = fitsimage.get_image() if image is None: return x, y = fitsimage.get_pan() points = fitsimage.get_pan_rect() # calculate pan position point radius p_image = paninfo.panimage.get_image() try: ...
KeyError
dataset/ETHPy150Open ejeschke/ginga/ginga/misc/plugins/Pan.py/Pan.panset
778
def test_class_object_qualname(self): # Test preservation of instance method __qualname__ attribute. try: __qualname__ = Original.original.__qualname__ except __HOLE__: pass else: self.assertEqual(Class.function.__qualname__, __qualname__)
AttributeError
dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_outer_staticmethod.py/TestNamingOuterStaticMethod.test_class_object_qualname
779
def test_instance_object_qualname(self): # Test preservation of instance method __qualname__ attribute. try: __qualname__ = Original().original.__qualname__ except __HOLE__: pass else: self.assertEqual(Class().function.__qualname__, __qualname__)
AttributeError
dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_outer_staticmethod.py/TestNamingOuterStaticMethod.test_instance_object_qualname
780
def enable_tty_echo(tty=None): """ Re-enables proper console behavior, primarily for when a reload is triggered at a PDB prompt. TODO: context manager for ignoring signals """ if tty is None: tty = sys.stdin if not tty.isatty(): return try: import termios exc...
ImportError
dataset/ETHPy150Open mahmoud/clastic/clastic/server.py/enable_tty_echo
781
def restart_with_reloader(error_func=None): to_mon = [] while 1: _log('info', ' * Clastic restarting with reloader') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value...
KeyboardInterrupt
dataset/ETHPy150Open mahmoud/clastic/clastic/server.py/restart_with_reloader
782
def run_with_reloader(main_func, extra_files=None, interval=1, error_func=None): signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) enable_tty_echo() if os.environ.get('WERKZEUG_RUN_MAIN') == 'true': thread.start_new_thread(main_func, ()) try: reloader...
KeyboardInterrupt
dataset/ETHPy150Open mahmoud/clastic/clastic/server.py/run_with_reloader
783
def process_queue(self): curr_time = time.time() elapsed = curr_time - self.last_time if elapsed < self.seconds: wait_ms = int(1000 * (self.seconds - elapsed)) else: wait_ms = 0 try: (fn, params) = self.queue.pop(0) self.processin...
IndexError
dataset/ETHPy150Open accerqueira/sublime-test-runner/test_runner/decorators.py/LazyDecorator.process_queue
784
def nn_setsockopt(socket, level, option, value): """set a socket option socket - socket number level - option level option - option value - a readable byte buffer (not a Unicode string) containing the value returns - 0 on success or < 0 on error """ try: return _nn_setsockopt(s...
TypeError
dataset/ETHPy150Open tonysimpson/nanomsg-python/_nanomsg_ctypes/__init__.py/nn_setsockopt
785
def nn_send(socket, msg, flags): "send a message" try: return _nn_send(socket, ctypes.addressof(msg), len(buffer(msg)), flags) except (__HOLE__, AttributeError): buf_msg = ctypes.create_string_buffer(msg) return _nn_send(socket, ctypes.addressof(buf_msg), len(msg), flags)
TypeError
dataset/ETHPy150Open tonysimpson/nanomsg-python/_nanomsg_ctypes/__init__.py/nn_send
786
def __get__(self, instance, owner): if instance is not None: try: return instance._data[self] except __HOLE__: return instance._data.setdefault(self, self._default(instance)) return self
KeyError
dataset/ETHPy150Open jaimegildesagredo/booby/booby/fields.py/Field.__get__
787
def __call_default(self, *args): try: return self.default() except TypeError as error: try: return self.default(*args) except __HOLE__: raise error
TypeError
dataset/ETHPy150Open jaimegildesagredo/booby/booby/fields.py/Field.__call_default
788
def test_credentials(self): logging.debug('') logging.debug('test_credentials') # Basic form. owner = Credentials() if sys.platform == 'win32' and not HAVE_PYWIN32: self.assertEqual('%s' % owner, owner.user+' (transient)') else: self.assertEqual('...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_rbac.py/TestCase.test_credentials
789
def fromPath(cls, path): """ @param path: A path object to use for both reading contents from and later saving to. @type path: L{FilePath} """ self = cls(path) try: fp = path.open() except __HOLE__: return self for line in ...
IOError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/client/knownhosts.py/KnownHostsFile.fromPath
790
def _pushWhitespaceBehavior(self, attr): """Push a new string onto the whitespaceBehaviorStack. The string's value is taken from the "xml:space" attribute, if it exists and has a legal value ("default" or "preserve"). Otherwise, the previous stack element is duplicated. """ assert len(self._whitespaceBeh...
KeyError
dataset/ETHPy150Open encorehu/django-buddy/core/aiml/AimlParser.py/AimlHandler._pushWhitespaceBehavior
791
def _startElement(self, name, attr): if name == "aiml": # <aiml> tags are only legal in the OutsideAiml state if self._state != self._STATE_OutsideAiml: raise AimlParserError, "Unexpected <aiml> tag "+self._location() self._state = self._STATE_InsideAiml self._insideTopic = False self._currentTopic...
KeyError
dataset/ETHPy150Open encorehu/django-buddy/core/aiml/AimlParser.py/AimlHandler._startElement
792
def _characters(self, ch): text = unicode(ch) if self._state == self._STATE_InsidePattern: # TODO: text inside patterns must be upper-case! self._currentPattern += text elif self._state == self._STATE_InsideThat: self._currentThat += text elif self._state == self._STATE_InsideTemplate: # First, see ...
IndexError
dataset/ETHPy150Open encorehu/django-buddy/core/aiml/AimlParser.py/AimlHandler._characters
793
def _validateElemStart(self, name, attr, version): """Test the validity of an element starting inside a <template> element. This function raises an AimlParserError exception if it the tag is invalid. Otherwise, no news is good news. """ # Check the element's attributes. Make sure that all required #...
IndexError
dataset/ETHPy150Open encorehu/django-buddy/core/aiml/AimlParser.py/AimlHandler._validateElemStart
794
def cast(self, d): """ Cast a single value to a :class:`datetime.date`. :param date_format: An optional :func:`datetime.strptime` format string for parsing datetimes in this column. :returns: :class:`datetime.date` or :code:`None`. """ ...
ValueError
dataset/ETHPy150Open wireservice/agate/agate/data_types/date.py/Date.cast
795
def load(self, filename, groups = None, moderators = ()): if PickleStorage.sharedDBs.has_key(filename): self.db = PickleStorage.sharedDBs[filename] else: try: self.db = pickle.load(open(filename)) PickleStorage.sharedDBs[filename] = self.db ...
IOError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/PickleStorage.load
796
def getModerator(self, groups): # first see if any groups are moderated. if so, nothing gets posted, # but the whole messages gets forwarded to the moderator address for group in groups: try: return self.dbm['moderators'][group] except __HOLE__: ...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.getModerator
797
def postRequest(self, message): cleave = message.find('\r\n\r\n') headers, article = message[:cleave], message[cleave + 4:] article = Article(headers, article) groups = article.getHeader('Newsgroups').split() xref = [] # Check for moderated status moderator = se...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.postRequest
798
def groupRequest(self, group): try: g = self.dbm['groups'][group] except __HOLE__: return defer.fail(NewsServerError("No such group: " + group)) else: flags = g.flags low = g.minArticle high = g.maxArticle num = high - low +...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.groupRequest
799
def articleRequest(self, group, index, id = None): if id is not None: try: xref = self.dbm['Message-IDs'][id] except KeyError: return defer.fail(NewsServerError("No such article: " + id)) else: group, index = xref[0] ...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.articleRequest