Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,700
def get_default_hub(): """Get default hub implementation """ names = [hub_name] if hub_name else ['pyuv_cffi', 'pyuv', 'epoll'] for name in names: try: module = importlib.import_module('guv.hubs.{}'.format(name)) log.debug('Hub: use {}'.format(name)) return m...
ImportError
dataset/ETHPy150Open veegee/guv/guv/hubs/hub.py/get_default_hub
5,701
def get_hub(): """Get the current event hub singleton object .. note :: |internal| """ try: hub = _threadlocal.hub except __HOLE__: # instantiate a Hub try: _threadlocal.Hub except AttributeError: use_hub() hub = _threadlocal.hub = _t...
AttributeError
dataset/ETHPy150Open veegee/guv/guv/hubs/hub.py/get_hub
5,702
def to_python(self, value): if value is None or value == '': return StreamValue(self.stream_block, []) elif isinstance(value, StreamValue): return value elif isinstance(value, string_types): try: unpacked_value = json.loads(value) e...
ValueError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailcore/fields.py/StreamField.to_python
5,703
def __virtual__(): ''' Only work on systems that are a proxy minion ''' try: if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'rest_sample': return __virtualname__ except __HOLE__: return (False, 'The rest_package execution module failed to load. Check the ...
KeyError
dataset/ETHPy150Open saltstack/salt/salt/modules/rest_package.py/__virtual__
5,704
def setUp(self): self.moderation = ModerationManager() self.moderation.register(ModelWithSlugField) self.filter_moderated_objects = ModelWithSlugField.objects.\ filter_moderated_objects def filter_moderated_objects(query_set): from moderation.models import MODERA...
ObjectDoesNotExist
dataset/ETHPy150Open dominno/django-moderation/tests/tests/unit/testregister.py/IntegrityErrorRegressionTestCase.setUp
5,705
def repeater(index): """repeats the last command with the given index """ global __last_commands__ try: call_data = __last_commands__[index] return call_data[0](*call_data[1], **call_data[2]) except __HOLE__: return None
IndexError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/repeater
5,706
@classmethod def generate_repr_of_all_references(cls, generate_gpu=True, generate_ass=True, skip_existing=False): """generates all representations of all references of this scene "...
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Reference.generate_repr_of_all_references
5,707
@classmethod def select_zero_uv_area_faces(cls): """selects faces with zero UV area """ def area(p): return 0.5 * abs(sum(x0 * y1 - x1 * y0 for ((x0, y0), (x1, y1)) in segments(p))) def segments(p): return zip(p, p[1:] + [p[0]...
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Modeling.select_zero_uv_area_faces
5,708
@classmethod def reset_tweaks(cls): """Resets the tweaks on the selected deformed objects """ for obj in pm.ls(sl=1): for tweak_node in pm.ls(obj.listHistory(), type=pm.nt.Tweak): try: for i in tweak_node.pl[0].cp.get(mi=1): ...
TypeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Rigging.reset_tweaks
5,709
@classmethod def convert_to_linear(cls): """adds a gamma_gain node in between the selected nodes outputs to make the result linear """ # # convert to linear # selection = pm.ls(sl=1) for file_node in selection: # get the connections ...
AttributeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Render.convert_to_linear
5,710
@classmethod def enable_matte(cls, color=0): """enables matte on selected objects """ # # Enable Matte on Selected Objects # colors = [ [0, 0, 0, 0], # Not Visible [1, 0, 0, 0], # Red [0, 1, 0, 0], # Green [0, 0, 1, 0...
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Render.enable_matte
5,711
@classmethod def enable_subdiv(cls): """enables subdiv on selected objects """ # # Set SubDiv to CatClark on Selected nodes # for node in pm.ls(sl=1): shape = node.getShape() try: shape.aiSubdivIterations.set(2) ...
AttributeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Render.enable_subdiv
5,712
@classmethod def normalize_sss_weights(cls): """normalizes the sss weights so their total weight is 1.0 if a aiStandard is assigned to the selected object it searches for an aiSkin in the emission channel. the script considers 0.7 as the highest diffuse value for aiStandard ...
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Render.normalize_sss_weights
5,713
@classmethod def move_cache_files(cls, source_driver, target_driver): """moves the selected cache files to another location :param source_driver: :param target_driver: :return: """ # # Move fur caches to new server # import os import s...
OSError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Render.move_cache_files
5,714
@classmethod def create_alembic(cls, from_top_node=1): """creates alembic cache from selected nodes """ import os root_flag = '-root %(node)s' mel_command = 'AbcExport -j "-frameRange %(start)s %(end)s -ro ' \ '-stripNamespaces -uvWrite -wholeFrameGeo -w...
OSError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Animation.create_alembic
5,715
@classmethod def copy_alembic_data(cls, source=None, target=None): """Copies alembic data from source to target hierarchy """ selection = pm.ls(sl=1) if not source or not target: source = selection[0] target = selection[1] # # Move Alembic Dat...
ValueError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/toolbox.py/Animation.copy_alembic_data
5,716
def _worker_start(): env = None policy = None max_length = None try: while True: msgs = {} # Only fetch the last message of each type while True: try: msg = queue.get_nowait() msgs[msg[0]] = msg[1:] ...
KeyboardInterrupt
dataset/ETHPy150Open rllab/rllab/rllab/plotter/plotter.py/_worker_start
5,717
def generate_gpu(self): """generates the GPU representation of the current scene """ # validate the version first self.version = self._validate_version(self.version) self.open_version(self.version) # load necessary plugins pm.loadPlugin('gpuCache') pm.lo...
OSError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/repr_tools.py/RepresentationGenerator.generate_gpu
5,718
@classmethod def clean_up(self): """cleans up the scene """ num_of_items_deleted = pm.mel.eval('MLdeleteUnused') logger.debug('deleting unknown references') delete_nodes_types = ['reference', 'unknown'] for node in pm.ls(type=delete_nodes_types): node.unl...
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/repr_tools.py/RepresentationGenerator.clean_up
5,719
def current_items(self, obj): """Display a list of the current position content Each item will be wrapped in a admin change form link if the item is editable via the admin. This list also only shows the first 5 items in order not to clutter up the admin change list. A horizonta...
AttributeError
dataset/ETHPy150Open callowayproject/django-kamasutra/positions/admin.py/PositionAdmin.current_items
5,720
def suggest_special(text): text = text.lstrip() cmd, _, arg = parse_special_command(text) if cmd == text: # Trying to complete the special command itself return (Special(),) if cmd in ('\\c', '\\connect'): return (Database(),) if cmd == '\\dn': return (Schema(),) ...
AttributeError
dataset/ETHPy150Open dbcli/pgcli/pgcli/packages/sqlcompletion.py/suggest_special
5,721
def test_textile(self): try: import textile except __HOLE__: textile = None textile_content = """Paragraph 1 Paragraph 2 with "quotes" and @code@""" t = Template("{{ textile_content|textile }}") rendered = t.render(Context(locals())).strip() if ...
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/lib/django/tests/regressiontests/markup/tests.py/Templates.test_textile
5,722
def test_markdown(self): try: import markdown except __HOLE__: markdown = None markdown_content = """Paragraph 1 ## An h2""" t = Template("{{ markdown_content|markdown }}") rendered = t.render(Context(locals())).strip() if markdown: ...
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/lib/django/tests/regressiontests/markup/tests.py/Templates.test_markdown
5,723
def test_docutils(self): try: import docutils except __HOLE__: docutils = None rest_content = """Paragraph 1 Paragraph 2 with a link_ .. _link: http://www.example.com/""" t = Template("{{ rest_content|restructuredtext }}") rendered = t.render(Context(l...
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/lib/django/tests/regressiontests/markup/tests.py/Templates.test_docutils
5,724
def subseq(self, start_offset=0, end_offset=None): """ Return a subset of the sequence starting at start_offset (defaulting to the beginning) ending at end_offset (None representing the end, whih is the default) Raises ValueError if duration_64 is missing on any element "...
KeyError
dataset/ETHPy150Open jtauber/sebastian/sebastian/core/elements.py/HSeq.subseq
5,725
def fetch_genes(id_list): """Fetch Entrez Gene records using Bio.Entrez, in particular epost (to submit the data to NCBI) and efetch to retrieve the information, then use Entrez.read to parse the data. Returns a list of parsed gene records. """ request = Entrez.epost("gene",id=",".join(id_lis...
RuntimeError
dataset/ETHPy150Open taoliu/taolib/Scripts/convert_gene_ids.py/fetch_genes
5,726
def parse_genes(genes): """Parse various gene information including: 1. Species name (taxonomy name) 2. Entrez gene ID 3. Official symbol 4. RefSeq IDs 5. Offical full name Basically, just to go through the parsed xml data.... A big headache to figure it out... Return a list of dictio...
KeyError
dataset/ETHPy150Open taoliu/taolib/Scripts/convert_gene_ids.py/parse_genes
5,727
def handle(self, *args, **options): raise CommandError( 'copy_group_data is currently broken. ' 'Ask Danny or Ethan to fix it along the lines of ' 'https://github.com/dimagi/commcare-hq/pull/9180/files#diff-9d976dc051a36a028c6604581dfbce5dR95' ) if len(args) ...
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/domainsync/management/commands/copy_group_data.py/Command.handle
5,728
def main(): try: si = None try: print "Trying to connect to VCENTER SERVER . . ." si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'], version="vim.version.version8") except __HOLE__, e: pass atex...
IOError
dataset/ETHPy150Open rreubenur/vmware-pyvmomi-examples/create_vswitch_and_portgroup.py/main
5,729
def _crosscat_metadata(self, bdb, generator_id): cc_cache = self._crosscat_cache(bdb) if cc_cache is not None and generator_id in cc_cache.metadata: return cc_cache.metadata[generator_id] sql = ''' SELECT metadata_json FROM bayesdb_crosscat_metadata WHERE ...
StopIteration
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/CrosscatMetamodel._crosscat_metadata
5,730
def _crosscat_theta(self, bdb, generator_id, modelno): cc_cache = self._crosscat_cache(bdb) if cc_cache is not None and \ generator_id in cc_cache.thetas and \ modelno in cc_cache.thetas[generator_id]: return cc_cache.thetas[generator_id][modelno] sql = ''' ...
StopIteration
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/CrosscatMetamodel._crosscat_theta
5,731
def register(self, bdb): with bdb.savepoint(): schema_sql = 'SELECT version FROM bayesdb_metamodel WHERE name = ?' cursor = bdb.sql_execute(schema_sql, (self.name(),)) version = None try: row = cursor.next() except __HOLE__: ...
StopIteration
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/CrosscatMetamodel.register
5,732
def logpdf_joint(self, bdb, generator_id, targets, constraints, modelno=None): M_c = self._crosscat_metadata(bdb, generator_id) try: for _, colno, value in constraints: crosscat_value_to_code(bdb, generator_id, M_c, colno, value) except KeyError: ...
KeyError
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/CrosscatMetamodel.logpdf_joint
5,733
def crosscat_value_to_code(bdb, generator_id, M_c, colno, value): stattype = core.bayesdb_generator_column_stattype(bdb, generator_id, colno) if stattype == 'categorical': # For hysterical raisins, code_to_value and value_to_code are # backwards. # # XXX Fix this. if valu...
TypeError
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/crosscat_value_to_code
5,734
def crosscat_cc_colno(bdb, generator_id, colno): sql = ''' SELECT cc_colno FROM bayesdb_crosscat_column WHERE generator_id = ? AND colno = ? ''' cursor = bdb.sql_execute(sql, (generator_id, colno)) try: row = cursor.next() except __HOLE__: generator = core.bayesdb...
StopIteration
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/crosscat_cc_colno
5,735
def crosscat_gen_colno(bdb, generator_id, cc_colno): sql = ''' SELECT colno FROM bayesdb_crosscat_column WHERE generator_id = ? AND cc_colno = ? ''' cursor = bdb.sql_execute(sql, (generator_id, cc_colno)) try: row = cursor.next() except __HOLE__: generator = core....
StopIteration
dataset/ETHPy150Open probcomp/bayeslite/src/metamodels/crosscat.py/crosscat_gen_colno
5,736
def _get_model(model_identifier): """ Helper to look up a model from an "app_label.module_name" string. """ try: Model = models.get_model(*model_identifier.split(".")) except __HOLE__: Model = None if Model is None: raise base.DeserializationError(u"Invalid model identifi...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/serializers/python.py/_get_model
5,737
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 agiliq/django-socialnews/socialnews/mptt/utils.py/previous_current_next
5,738
def lastfm_get_tree(method, **kwargs): for k, v in kwargs.items(): kwargs[k] = unicode(v).encode('utf-8') url = 'http://ws.audioscrobbler.com/2.0/?api_key=%s&method=%s&%s' % ( settings.LASTFM_API_KEY, method, urllib.urlencode(kwargs) ) print url try: tre...
IOError
dataset/ETHPy150Open jpic/playlistnow.fm/apps/music/lastfm_api.py/lastfm_get_tree
5,739
@classmethod def utcfromtimestamp(cls, timestamp, allow_future=False): """Converts a str or int epoch time to datetime. Note: this method drops ms from timestamps. Args: timestamp: str, int, or float epoch timestamp. allow_future: boolean, default False, True to allow future timestamps. ...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/common/util.py/Datetime.utcfromtimestamp
5,740
def Serialize(obj): """Return a binary serialized version of object. Depending on the serialization method, some complex objects or input formats may not be serializable. UTF-8 strings (by themselves or in other structures e.g. lists) are always supported. Args: obj: any object Returns: str, po...
TypeError
dataset/ETHPy150Open google/simian/src/simian/mac/common/util.py/Serialize
5,741
def Deserialize(s, parse_float=float): """Return an object for a binary serialized version. Depending on the target platform, precision of float values may be lowered on deserialization. Use parse_float to provide an alternative floating point translation function, e.g. decimal.Decimal, if retaining high le...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/common/util.py/Deserialize
5,742
@classmethod def get_row_by_pk(self, ar, pk): """ `dbtables.Table` overrides this. """ try: return ar.data_iterator[int(pk)-1] except (__HOLE__, IndexError): return None
ValueError
dataset/ETHPy150Open lsaffre/lino/lino/core/tables.py/AbstractTable.get_row_by_pk
5,743
def parse_str(string): try: return float(string) except __HOLE__: prefixes = dict(prefixes_SI.items() + prefixes_IEC.items()) for prefix, val in prefixes.items(): if string.endswith(prefix): return float(string.replace(prefix, '')) * val raise Exception("I...
ValueError
dataset/ETHPy150Open vimeo/graph-explorer/graph_explorer/convert.py/parse_str
5,744
def __new__(cls, config=None, **kwargs): """Immutable constructor. If 'config' is non-None all configuration options will default to the value it contains unless the configuration option is explicitly set to 'None' in the keyword arguments. If 'config' is None then all configuration options default...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/datastore/datastore_rpc.py/BaseConfiguration.__new__
5,745
def _remove_pending(self, rpc): """Remove an RPC object from the list of pending RPCs. If the argument is a MultiRpc object, the wrapped RPCs are removed from the list of pending RPCs. """ if isinstance(rpc, MultiRpc): for wrapped_rpc in rpc._MultiRpc__rpcs: self._remove_pending(wra...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/datastore/datastore_rpc.py/BaseConnection._remove_pending
5,746
def execute_request(self, request): try: # This is how the carbon graphite server parses the line. We could be more forgiving but if it works # for them, then we can do it as well. metric, value, orig_timestamp = request.strip().split() value = float(value) ...
ValueError
dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/builtin_monitors/graphite_monitor.py/GraphiteTextServer.execute_request
5,747
def execute_request(self, request): # noinspection PyBroadException try: # Use pickle to read the binary data. data_object = pickle.loads(request) except: # pickle.loads is document as raising any type of exception, so have to catch them all. self.__logger.w...
ValueError
dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/builtin_monitors/graphite_monitor.py/GraphitePickleServer.execute_request
5,748
def get_proxy(self): """ cycly generate the proxy server string """ try: proxy = next(self.it_proxy) LOG.debug('fetched proxy : %s' % proxy) return proxy except __HOLE__: LOG.debug('.... re-iterating proxies') self.it_pr...
StopIteration
dataset/ETHPy150Open sk1418/zhuaxia/zhuaxia/proxypool.py/ProxyPool.get_proxy
5,749
def run_single_instance(self, args): # code for single instance of the application # based on the C++ solution available at # http://wiki.qtcentre.org/index.php?title=SingleApplication if QtCore.QT_VERSION >= 0x40400: self._unique_key = os.path.join(system.home_directory(), ...
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/application.py/VistrailsApplicationSingleton.run_single_instance
5,750
def parse_input_args_from_other_instance(self, msg): options_re = re.compile(r"^(\[('([^'])*', ?)*'([^']*)'\])|(\[\s?\])$") if options_re.match(msg): #it's safe to eval as a list args = literal_eval(msg) if isinstance(args, list): try: ...
SystemExit
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/application.py/VistrailsApplicationSingleton.parse_input_args_from_other_instance
5,751
def linux_default_application_set(): """linux_default_application_set() -> True|False|None For Linux - checks if a handler is set for .vt and .vtl files. """ command = ['xdg-mime', 'query', 'filetype', os.path.join(system.vistrails_root_directory(), 'tests', 'r...
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/application.py/linux_default_application_set
5,752
def linux_update_default_application(): """ update_default_application() -> None For Linux - checks if we should install vistrails as the default application for .vt and .vtl files. If replace is False, don't replace an existing handler. Returns True if installation succeeded. """ root = sy...
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/application.py/linux_update_default_application
5,753
def _show_completions(self, view): try: # TODO: We probably should show completions after other chars. is_after_dot = view.substr(view.sel()[0].b - 1) == '.' except __HOLE__: return if not is_after_dot: return if not AnalysisServer.ping()...
IndexError
dataset/ETHPy150Open guillermooo/dart-sublime-bundle/autocomplete.py/DartIdleAutocomplete._show_completions
5,754
def _in_string_or_comment(self, view): try: return view.match_selector(view.sel()[0].b, 'source.dart string, source.dart comment') except __HOLE__: pass
IndexError
dataset/ETHPy150Open guillermooo/dart-sublime-bundle/autocomplete.py/DartIdleAutocomplete._in_string_or_comment
5,755
def __getitem__(self, key): try: processor, obj, index = self._keymap[key] except __HOLE__: processor, obj, index = self._parent._key_fallback(key) except TypeError: if isinstance(key, slice): l = [] ...
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/BaseRowProxy.__getitem__
5,756
def __getattr__(self, name): try: return self[name] except __HOLE__ as e: raise AttributeError(e.args[0])
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/BaseRowProxy.__getattr__
5,757
def __init__(self, parent, metadata): self._processors = processors = [] # We do not strictly need to store the processor in the key mapping, # though it is faster in the Python version (probably because of the # saved attribute lookup self._processors) self._keymap = keymap = {...
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/ResultMetaData.__init__
5,758
def _fetchone_impl(self): try: return self.cursor.fetchone() except __HOLE__: self._non_result()
AttributeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/ResultProxy._fetchone_impl
5,759
def _fetchmany_impl(self, size=None): try: if size is None: return self.cursor.fetchmany() else: return self.cursor.fetchmany(size) except __HOLE__: self._non_result()
AttributeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/ResultProxy._fetchmany_impl
5,760
def _fetchall_impl(self): try: return self.cursor.fetchall() except __HOLE__: self._non_result()
AttributeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/result.py/ResultProxy._fetchall_impl
5,761
def play_sound_file(self, data, rate, ssize, nchannels): try: dsp = ossaudiodev.open('w') except __HOLE__, msg: if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise unittest.SkipTest(msg) raise...
IOError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_ossaudiodev.py/OSSAudioDevTests.play_sound_file
5,762
def test_main(): try: dsp = ossaudiodev.open('w') except (ossaudiodev.error, __HOLE__), msg: if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise unittest.SkipTest(msg) raise dsp.close() test_support.run_unittest(...
IOError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_ossaudiodev.py/test_main
5,763
def getconfig(func): if func.__name__.startswith('help') or func.__name__ in ('version',): return func def inner(*args, **kwargs): try: repo = Repository(kwargs['config'], kwargs['define']) except NomadIniNotFound as e: sys.stderr.write("Create '%s' to use nomad,...
IOError
dataset/ETHPy150Open piranha/nomad/nomad/__init__.py/getconfig
5,764
@app.command() def create(name, dependencies=('d', [], 'migration dependencies'), prefix_date=('p', False, 'prefix migration name with date'), **opts): '''Create new migration ''' repo = opts['repo'] deps = map(repo.get, dependencies) if prefix_date: name = ...
OSError
dataset/ETHPy150Open piranha/nomad/nomad/__init__.py/create
5,765
def _state_session(state): """Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. """ if state.session_id: try: return _sessions[state.session_id] except __HOLE__: pass return None
KeyError
dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/sqlalchemy/orm/session.py/_state_session
5,766
def main(argv=sys.argv[1:]): myapp = MusubiApp() if len(argv): try: return myapp.run(argv) except __HOLE__, err: #Command does not exist MusubiApp.log.error(err) sys.exit(2) except KeyboardInterrupt, err: MusubiApp.log.error(err...
ValueError
dataset/ETHPy150Open cakebread/musubi/musubi/main.py/main
5,767
def fit_regularized(self, start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=True, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=1e-4, qc_tol=0.03, qc_verbose=False...
TypeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/discrete/discrete_model.py/DiscreteModel.fit_regularized
5,768
def _handle_data(self, endog, exog, missing, hasconst, **kwargs): if data_tools._is_using_ndarray_type(endog, None): endog_dummies, ynames = _numpy_to_dummies(endog) yname = 'y' elif data_tools._is_using_pandas(endog, None): endog_dummies, ynames, yname = _pandas_to_d...
KeyError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/discrete/discrete_model.py/MultinomialModel._handle_data
5,769
def __getstate__(self): try: #remove unpicklable callback self.mle_settings['callback'] = None except (__HOLE__, KeyError): pass return self.__dict__
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/discrete/discrete_model.py/DiscreteResults.__getstate__
5,770
def _maybe_convert_ynames_int(self, ynames): # see if they're integers try: for i in ynames: if ynames[i] % 1 == 0: ynames[i] = str(int(ynames[i])) except __HOLE__: pass return ynames
TypeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/discrete/discrete_model.py/MultinomialResults._maybe_convert_ynames_int
5,771
def __init__(self, r_or_colorstr, g=None, b=None, a=None): if isinstance(r_or_colorstr, str): assert g is b is a is None, "Ambiguous color arguments" self.r, self.g, self.b, self.a = self._parse_colorstr(r_or_colorstr) elif g is b is a is None: try: self.r, self.g, self.b, self.a = r_or_colorstr ex...
ValueError
dataset/ETHPy150Open caseman/grease/grease/color.py/RGBA.__init__
5,772
def build_pot_file(self, localedir): file_list = self.find_files(".") potfile = os.path.join(localedir, '%s.pot' % str(self.domain)) if os.path.exists(potfile): # Remove a previous undeleted potfile, if any os.unlink(potfile) for f in file_list: try:...
UnicodeDecodeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/core/management/commands/makemessages.py/Command.build_pot_file
5,773
def it_should_be_iterable(self): srels = _SerializedRelationshipCollection() try: for x in srels: pass except __HOLE__: msg = "_SerializedRelationshipCollection object is not iterable" pytest.fail(msg) # fixtures --------------------------...
TypeError
dataset/ETHPy150Open scanny/python-pptx/tests/opc/test_pkgreader.py/Describe_SerializedRelationshipCollection.it_should_be_iterable
5,774
def load_raw_results(self): self.experiments = [] for i in range(len(self.folders)): filename = self.folders[i] + Experiment.experiment_output_folder + \ os.sep + Experiment.erperiment_output_filename try: f = open(filename , "r")...
IOError
dataset/ETHPy150Open karlnapf/kameleon-mcmc/kameleon_mcmc/experiments/ExperimentAggregator.py/ExperimentAggregator.load_raw_results
5,775
def handle(self, filepath, cols): credentials = [] with open(filepath) as csv_file: reader = unicode_csv_reader(csv_file) try: next(reader) except __HOLE__: raise ValueError('empty csv file: %s' % filepath) for row in reader...
StopIteration
dataset/ETHPy150Open marcwebbie/passpie/passpie/importers/csv_importer.py/CSVImporter.handle
5,776
def get_raw_data(self, datum): """Returns the raw data for this column, before any filters or formatting are applied to it. This is useful when doing calculations on data in the table. """ # Callable transformations if callable(self.transform): data = self.tra...
AttributeError
dataset/ETHPy150Open CiscoSystems/avos/horizon/tables/base.py/Column.get_raw_data
5,777
def get_summation(self): """Returns the summary value for the data in this column if a valid summation method is specified for it. Otherwise returns ``None``. """ if self.summation not in self.summation_methods: return None summation_function = self.summation_methods...
TypeError
dataset/ETHPy150Open CiscoSystems/avos/horizon/tables/base.py/Column.get_summation
5,778
@staticmethod def parse_action(action_string): """Parses the ``action`` parameter (a string) sent back with the POST data. By default this parses a string formatted as ``{{ table_name }}__{{ action_name }}__{{ row_id }}`` and returns each of the pieces. The ``row_id`` is optional. ...
IndexError
dataset/ETHPy150Open CiscoSystems/avos/horizon/tables/base.py/DataTable.parse_action
5,779
@staticmethod def __add_body_from_string(args, body, proxy): proxy.append(JMX._bool_prop("HTTPSampler.postBodyRaw", True)) coll_prop = JMX._collection_prop("Arguments.arguments") header = JMX._element_prop("elementProp", "HTTPArgument") try: header.append(JMX._string_prop...
ValueError
dataset/ETHPy150Open Blazemeter/taurus/bzt/jmx.py/JMX.__add_body_from_string
5,780
@staticmethod def __add_body_from_script(args, body, proxy): http_args_coll_prop = JMX._collection_prop("Arguments.arguments") for arg_name, arg_value in body.items(): try: http_element_prop = JMX._element_prop(arg_name, "HTTPArgument") except __HOLE__: ...
ValueError
dataset/ETHPy150Open Blazemeter/taurus/bzt/jmx.py/JMX.__add_body_from_script
5,781
@staticmethod def __add_hostnameport_2sampler(parsed_url, proxy, url): if parsed_url.scheme: proxy.append(JMX._string_prop("HTTPSampler.protocol", parsed_url.scheme)) if parsed_url.netloc: netloc_parts = parsed_url.netloc.split(':') if netloc_parts[0]: ...
ValueError
dataset/ETHPy150Open Blazemeter/taurus/bzt/jmx.py/JMX.__add_hostnameport_2sampler
5,782
def string_io(data=None): # cStringIO can't handle unicode ''' Pass data through to stringIO module and return result ''' try: return cStringIO(bytes(data)) except (UnicodeEncodeError, __HOLE__): return StringIO(data)
TypeError
dataset/ETHPy150Open saltstack/salt/salt/_compat.py/string_io
5,783
def test_avg_std(self): # Use integration to test distribution average and standard deviation. # Only works for distributions which do not consume variates in pairs g = random.Random() N = 5000 x = [i/float(N) for i in range(1,N)] for variate, args, mu, sigmasqrd in [ ...
IndexError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_random.py/TestDistributions.test_avg_std
5,784
def run_query(self, query): connection = None try: connection = connect(**self.configuration.to_dict()) cursor = connection.cursor() cursor.execute(query) column_names = [] columns = [] for column in cursor.description: ...
KeyboardInterrupt
dataset/ETHPy150Open getredash/redash/redash/query_runner/impala_ds.py/Impala.run_query
5,785
def get_filediff(self, request, *args, **kwargs): """Returns the FileDiff, or an error, for the given parameters.""" draft_resource = resources.review_request_draft try: draft = draft_resource.get_object(request, *args, **kwargs) except ObjectDoesNotExist: return...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/draft_original_file.py/DraftOriginalFileResource.get_filediff
5,786
@app.route('/api/store/', methods=['POST']) def store(): """ Accepts a gzipped JSON POST body. If ``PUBLIC_WRITES`` is truthy, the Authorization header is ignored. Format resembles the following: >>> { >>> "event_type": "Exception", >>> "tags": [ ["level", "error"], ["...
ValueError
dataset/ETHPy150Open dcramer/sentry-old/sentry/collector/views.py/store
5,787
def get_command(self, ctx, name): try: if sys.version_info[0] == 2: name = name.encode('ascii', 'replace') mod = __import__('complex.commands.cmd_' + name, None, None, ['cli']) except __HOLE__: return return mod.cli
ImportError
dataset/ETHPy150Open pallets/click/examples/complex/complex/cli.py/ComplexCLI.get_command
5,788
def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None): ''' Compare different libcloud versions ''' if not HAS_LIBCLOUD: return False if not isinstance(reqver, (list, tuple)): raise RuntimeError( '\'reqver\' needs to passed as a tuple or list, i.e., (0, 14...
ImportError
dataset/ETHPy150Open saltstack/salt/salt/cloud/libcloudfuncs.py/check_libcloud_version
5,789
def create_directory(class_name, output): output_name = output if output_name[-1] != "/": output_name = output_name + "/" pathdir = output_name + class_name try: if not os.path.exists(pathdir): os.makedirs(pathdir) except __HOLE__: # FIXME pass
OSError
dataset/ETHPy150Open androguard/androguard/androdd.py/create_directory
5,790
def clean_upload(self): dirs_do_delete = [ appengine_rocket_engine, appengine_libs, virtualenv_appengine_libs ] for path in dirs_do_delete: try: shutil.rmtree(path) except __HOLE__: pass
OSError
dataset/ETHPy150Open xando/django-rocket-engine/rocket_engine/management/commands/appengine.py/Command.clean_upload
5,791
def update(self, argv): self.clean_upload() try: self.prepare_upload() try: get_callable(PRE_UPDATE_HOOK)() except (AttributeError, ImportError): pass appcfg.main(argv[1:] + [PROJECT_DIR]) try: ...
ImportError
dataset/ETHPy150Open xando/django-rocket-engine/rocket_engine/management/commands/appengine.py/Command.update
5,792
def _to_node(self, data): if data: try: state = self.NODE_STATE_MAP[data['status']] except KeyError: state = NodeState.UNKNOWN if 'server' not in data: # Response does not contain server UUID if the server # cre...
ValueError
dataset/ETHPy150Open apache/libcloud/libcloud/compute/drivers/cloudsigma.py/CloudSigma_1_0_NodeDriver._to_node
5,793
def run_srb(self, *argv, **kwargs): if len(argv) == 1 and isinstance(argv[0], six.string_types): # convert a single string to a list argv = shlex.split(argv[0]) mock_stdout = six.StringIO() mock_stderr = six.StringIO() if 'exp_results' in kwargs: exp_...
SystemExit
dataset/ETHPy150Open openstack/swift/test/unit/cli/test_ringbuilder.py/RunSwiftRingBuilderMixin.run_srb
5,794
def tearDown(self): try: shutil.rmtree(self.tmpdir, True) except __HOLE__: pass
OSError
dataset/ETHPy150Open openstack/swift/test/unit/cli/test_ringbuilder.py/TestCommands.tearDown
5,795
def create_sample_ring(self, part_power=6): """ Create a sample ring with four devices At least four devices are needed to test removing a device, since having less devices than replicas is not allowed. """ # Ensure there is no existing test builder file because ...
OSError
dataset/ETHPy150Open openstack/swift/test/unit/cli/test_ringbuilder.py/TestCommands.create_sample_ring
5,796
def tearDown(self): try: shutil.rmtree(self.tmpdir, True) except __HOLE__: pass
OSError
dataset/ETHPy150Open openstack/swift/test/unit/cli/test_ringbuilder.py/TestRebalanceCommand.tearDown
5,797
def run_srb(self, *argv): mock_stdout = six.StringIO() mock_stderr = six.StringIO() srb_args = ["", self.tempfile] + [str(s) for s in argv] try: with mock.patch("sys.stdout", mock_stdout): with mock.patch("sys.stderr", mock_stderr): ringb...
SystemExit
dataset/ETHPy150Open openstack/swift/test/unit/cli/test_ringbuilder.py/TestRebalanceCommand.run_srb
5,798
def _sort_gens(gens, **args): """Sort generators in a reasonably intelligent way. """ opt = build_options(args) gens_order, wrt = {}, None if opt is not None: gens_order, wrt = {}, opt.wrt for i, gen in enumerate(opt.sort): gens_order[gen] = i + 1 def order_key(gen): ...
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/polys/polyutils.py/_sort_gens
5,799
def _parallel_dict_from_expr_if_gens(exprs, opt): """Transform expressions into a multinomial form given generators. """ k, indices = len(opt.gens), {} for i, g in enumerate(opt.gens): indices[g] = i polys = [] for expr in exprs: poly = {} if expr.is_Equality: ...
KeyError
dataset/ETHPy150Open sympy/sympy/sympy/polys/polyutils.py/_parallel_dict_from_expr_if_gens