Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,800
def _dict_from_expr(expr, opt): """Transform an expression into a multinomial form. """ if expr.is_commutative is False: raise PolynomialError('non-commutative expressions are not supported') def _is_expandable_pow(expr): return (expr.is_Pow and expr.exp.is_positive and expr.exp.is_Integer ...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/polys/polyutils.py/_dict_from_expr
5,801
def _dict_reorder(rep, gens, new_gens): """Reorder levels using dict representation. """ gens = list(gens) monoms = rep.keys() coeffs = rep.values() new_monoms = [ [] for _ in range(len(rep)) ] used_indices = set() for gen in new_gens: try: j = gens.index(gen) ...
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/polys/polyutils.py/_dict_reorder
5,802
def __setstate__(self, d): # All values that were pickled are now assigned to a fresh instance for name, value in d.items(): try: setattr(self, name, value) except __HOLE__: # This is needed in cases like Rational :> Half pass
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/polys/polyutils.py/PicklableWithSlots.__setstate__
5,803
def started(self, *args): try: code = int(sys.argv[1]) except __HOLE__: code = sys.argv[1] raise SystemExit(code)
ValueError
dataset/ETHPy150Open circuits/circuits/tests/core/exitcodeapp.py/App.started
5,804
def is_numeric(s): """Determine if a string is numeric""" try: float(s) return True except __HOLE__: return False;
ValueError
dataset/ETHPy150Open briandconnelly/BEACONToolkit/plotting/scripts/plot_csv.py/is_numeric
5,805
def plot_csv(): """Plot CSV data""" parser = argparse.ArgumentParser(description='Create plots from CSV data', version='{v}'.format(v=__version__)) parser.add_argument('outfile', action='store', help='output file') parser.add_argument('-i', '--infile', type=argparse.FileType('rb'), default=sys.stdin, he...
AttributeError
dataset/ETHPy150Open briandconnelly/BEACONToolkit/plotting/scripts/plot_csv.py/plot_csv
5,806
@application.route('/', methods=['GET', 'POST']) def index(): """ Main WSGI application entry. """ path = normpath(abspath(dirname(__file__))) hooks = join(path, 'hooks') # Only POST is implemented if request.method != 'POST': abort(501) # Load config with open(join(path, ...
KeyError
dataset/ETHPy150Open carlos-jenkins/python-github-webhooks/webhooks.py/index
5,807
@click.command() @click.argument('location', type=click.Path(), default='./chanjo-demo', required=False) @click.pass_context def demo(context, location): """Copy demo files to a directory. \b LOCATION: directory to add demofiles to (default: ./chanjo-demo) """ user_dir = path(locati...
OSError
dataset/ETHPy150Open robinandeer/chanjo/chanjo/demo/cli.py/demo
5,808
def _processSingleResult(self,resultType,resultItem): if _entryResultTypes.has_key(resultType): # Search continuations are ignored dn,entry = resultItem self.allEntries[dn] = entry for a in self.indexed_attrs: if entry.has_key(a): for v in entry[a]: try: ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/python-ldap-2.3.13/Lib/ldap/async.py/IndexedDict._processSingleResult
5,809
def download_md5(uri, dest): """ downloads file from uri to file dest """ # Create intermediate directories as necessary, #2970 dirname = os.path.dirname(dest) if len(dirname): try: os.makedirs(dirname) except __HOLE__ as e: if e.errno != errno.EEXIST: ...
OSError
dataset/ETHPy150Open ros/catkin/cmake/test/download_checkmd5.py/download_md5
5,810
def get_entity_by_key(self, key): try: identifier = self.reverse_cache[key][0] except __HOLE__: return None return self.get_entity(identifier)
KeyError
dataset/ETHPy150Open potatolondon/djangae/djangae/db/backends/appengine/context.py/Context.get_entity_by_key
5,811
def FromJsonString(self, value): """Converts a string to Duration. Args: value: A string to be converted. The string must end with 's'. Any fractional digits (or none) are accepted as long as they fit into precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s Raises: ...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/net/proto2/python/internal/well_known_types.py/Duration.FromJsonString
5,812
def _build(self, build_method): """ build image from provided build_args :return: BuildResults """ logger.info("building image '%s'", self.image) self._ensure_not_built() self.temp_dir = tempfile.mkdtemp() temp_path = os.path.join(self.temp_dir, BUILD_JSO...
KeyboardInterrupt
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/outer.py/BuildManager._build
5,813
def main(): # Define default configuration location parser = OptionParser(usage="usage: %prog [options] /path/to/file") parser.add_option("-d", "--debug", action="store_true", dest="debug", help="enable debug messages to the console.") p...
KeyboardInterrupt
dataset/ETHPy150Open lmco/laikaboss/laika.py/main
5,814
def run(self): try: from progressbar import ProgressBar, Bar, Counter, Timer, ETA, Percentage, RotatingMarker widgets = [Percentage(), Bar(left='[', right=']'), ' Processed: ', Counter(), '/', "%s" % self.task_count, ' total files (', Timer(), ') ', ETA()] pb = ProgressBar(wi...
ImportError
dataset/ETHPy150Open lmco/laikaboss/laika.py/QueueMonitor.run
5,815
def run(self): global CONFIG_PATH config.init(path=CONFIG_PATH) init_logging() ret_value = 0 # Loop and accept messages from both channels, acting accordingly while True: next_task = self.task_queue.get() if next_task is None: # Po...
IOError
dataset/ETHPy150Open lmco/laikaboss/laika.py/Consumer.run
5,816
def test_install_requirements_parsing(self): mock = MagicMock(return_value={'retcode': 0, 'stdout': ''}) pip_list = MagicMock(return_value={'pep8': '1.3.3'}) with patch.dict(pip_state.__salt__, {'cmd.run_all': mock, 'pip.list': pip_list}): ...
AttributeError
dataset/ETHPy150Open saltstack/salt/tests/unit/states/pip_test.py/PipStateTest.test_install_requirements_parsing
5,817
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__, epilog=_USAGE_EXAMPLES) parser.add_argument( 'destination', metavar="destination", type=str, help="address of the Phabricator instance...
KeyboardInterrupt
dataset/ETHPy150Open bloomberg/phabricator-tools/py/pig/pigcmd_phabping.py/main
5,818
def _get_post_clean_step_hook(node): """Get post clean step hook for the currently executing clean step. This method reads node.clean_step and returns the post clean step hook for the currently executing clean step. :param node: a node object :returns: a method if there is a post clean step hook f...
KeyError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/agent_base_vendor.py/_get_post_clean_step_hook
5,819
@base.passthru(['POST']) @task_manager.require_exclusive_lock def heartbeat(self, task, **kwargs): """Method for agent to periodically check in. The agent should be sending its agent_url (so Ironic can talk back) as a kwarg. kwargs should have the following format:: { ...
KeyError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/agent_base_vendor.py/BaseAgentVendor.heartbeat
5,820
def _get_interfaces(self, inventory): interfaces = [] try: interfaces = inventory['interfaces'] except (__HOLE__, TypeError): raise exception.InvalidParameterValue(_( 'Malformed network interfaces lookup: %s') % inventory) return interfaces
KeyError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/agent_base_vendor.py/BaseAgentVendor._get_interfaces
5,821
def _request(self, url, method, **kwargs): if self.timeout is not None: kwargs.setdefault('timeout', self.timeout) kwargs.setdefault('headers', kwargs.get('headers', {})) kwargs['headers']['User-Agent'] = self.user_agent try: if kwargs['body'] is 'json': ...
KeyError
dataset/ETHPy150Open dmsimard/python-cephclient/cephclient/client.py/CephClient._request
5,822
def log_wrapper(self): """ Wrapper to set logging parameters for output """ log = logging.getLogger('client.py') # Set the log format and log level try: debug = self.params["debug"] log.setLevel(logging.DEBUG) except __HOLE__: ...
KeyError
dataset/ETHPy150Open dmsimard/python-cephclient/cephclient/client.py/CephClient.log_wrapper
5,823
def _clean (self, *filenames): if not filenames: filenames = self.temp_files self.temp_files = [] log.info("removing: %s", string.join(filenames)) for filename in filenames: try: os.remove(filename) except __HOLE__: ...
OSError
dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/command/config.py/config._clean
5,824
def check(validator, value, *args, **kwargs): """Call a validator and return True if it's valid, False otherwise. The first argument is the validator, the second a value. All other arguments are forwarded to the validator function. >>> check(is_valid_email, 'foo@bar.com') True """ try: validator(*ar...
ValidationError
dataset/ETHPy150Open IanLewis/kay/kay/utils/validators.py/check
5,825
@cacheit def _simplify_delta(expr): """ Rewrite a KroneckerDelta's indices in its simplest form. """ from sympy.solvers import solve if isinstance(expr, KroneckerDelta): try: slns = solve(expr.args[0] - expr.args[1], dict=True) if slns and len(slns) == 1: ...
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/concrete/delta.py/_simplify_delta
5,826
@cacheit def deltaproduct(f, limit): """ Handle products containing a KroneckerDelta. See Also ======== deltasummation sympy.functions.special.tensor_functions.KroneckerDelta sympy.concrete.products.product """ from sympy.concrete.products import product if ((limit[2] - limit[...
AssertionError
dataset/ETHPy150Open sympy/sympy/sympy/concrete/delta.py/deltaproduct
5,827
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, **adapter_kwargs): """Receives a Response. Returns a generator of Responses.""" i = 0 hist = [] # keep track of history while resp.is_redirect: ...
KeyError
dataset/ETHPy150Open BergWerkGIS/QGIS-CKAN-Browser/CKAN-Browser/request/sessions.py/SessionRedirectMixin.resolve_redirects
5,828
def rebuild_proxies(self, prepared_request, proxies): """ This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this ...
KeyError
dataset/ETHPy150Open BergWerkGIS/QGIS-CKAN-Browser/CKAN-Browser/request/sessions.py/SessionRedirectMixin.rebuild_proxies
5,829
def ask_key(): if Terminal is None: try: value = raw_input( "Type the decryption key, " "without spaces or other special characters: ") return value.strip().decode('hex') except __HOLE__: return None sys.__stdin__ = sys.stdin ...
TypeError
dataset/ETHPy150Open longaccess/longaccess-client/lacli/certinput.py/ask_key
5,830
def _inTxn(func): def wrapped(self, *args, **kwargs): return self._callInTransaction(func, self, *args, **kwargs) if hasattr(func, '__name__'): try: wrapped.__name__ = func.__name__[4:] except __HOLE__: pass if hasattr(func, '__doc__'): wrapped.__doc...
TypeError
dataset/ETHPy150Open CollabQ/CollabQ/openid/store/sqlstore.py/_inTxn
5,831
def _getSQL(self, sql_name): try: return self._statement_cache[sql_name] except __HOLE__: sql = getattr(self, sql_name) sql %= self._table_names self._statement_cache[sql_name] = sql return sql
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/openid/store/sqlstore.py/SQLStore._getSQL
5,832
def blobEncode(self, blob): try: from psycopg2 import Binary except __HOLE__: from psycopg import Binary return Binary(blob)
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/openid/store/sqlstore.py/PostgreSQLStore.blobEncode
5,833
def get(self, orig_key): """Get cache entry for key, or return None.""" resp = requests.Response() key = self._clean_key(orig_key) path = os.path.join(self.cache_dir, key) try: with open(path, 'rb') as f: # read lines one at a time wh...
IOError
dataset/ETHPy150Open jamesturk/scrapelib/scrapelib/cache.py/FileCache.get
5,834
def load_marathon_config(path=PATH_TO_MARATHON_CONFIG): try: with open(path) as f: return MarathonConfig(json.load(f), path) except __HOLE__ as e: raise PaastaNotConfiguredError("Could not load marathon config file %s: %s" % (e.filename, e.strerror))
IOError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/marathon_tools.py/load_marathon_config
5,835
def get_url(self): """Get the Marathon API url :returns: The Marathon API endpoint""" try: return self['url'] except __HOLE__: raise MarathonNotConfigured('Could not find marathon url in system marathon config: %s' % self.path)
KeyError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/marathon_tools.py/MarathonConfig.get_url
5,836
def get_username(self): """Get the Marathon API username :returns: The Marathon API username""" try: return self['user'] except __HOLE__: raise MarathonNotConfigured('Could not find marathon user in system marathon config: %s' % self.path)
KeyError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/marathon_tools.py/MarathonConfig.get_username
5,837
def get_password(self): """Get the Marathon API password :returns: The Marathon API password""" try: return self['password'] except __HOLE__: raise MarathonNotConfigured('Could not find marathon password in system marathon config: %s' % self.path)
KeyError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/marathon_tools.py/MarathonConfig.get_password
5,838
def get_marathon_services_running_here_for_nerve(cluster, soa_dir): if not cluster: try: cluster = load_system_paasta_config().get_cluster() # In the cases where there is *no* cluster or in the case # where there isn't a Paasta configuration file at *all*, then # there mu...
KeyError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/marathon_tools.py/get_marathon_services_running_here_for_nerve
5,839
def register_service(name, regtype, port): def register_callback(sdRef, flags, errorCode, name, regtype, domain): if errorCode == pybonjour.kDNSServiceErr_NoError: logger.debug('Registered bonjour service %s.%s', name, regtype) record = pybonjour.TXTRecord(appletv.DEVICE_INFO) serv...
KeyboardInterrupt
dataset/ETHPy150Open pascalw/Airplayer/airplayer/bonjour.py/register_service
5,840
def send_message(self, message): headers = self._headers.copy() headers['Content-Length'] = len(message) self._setup_opener() request = Request(self.endpoint, data=message, headers=headers) try: # install_opener is ignored in > 2.7.9 when an SSLContext is passed to ...
HTTPError
dataset/ETHPy150Open diyan/pywinrm/winrm/transport.py/HttpPlaintext.send_message
5,841
def send_message(self, message): # TODO current implementation does negotiation on each HTTP request # which is not efficient # TODO support kerberos session with message encryption krb_ticket = KerberosTicket(self.krb_service) headers = {'Authorization': krb_ticket.auth_header, ...
HTTPError
dataset/ETHPy150Open diyan/pywinrm/winrm/transport.py/HttpKerberos.send_message
5,842
def objGetChildren(self, obj): """Return dictionary with attributes or contents of object.""" # print 'objGetChildren ', obj otype = type(obj) d = {} if (obj is None or obj is False or obj is True): return d self.ntop = 0 if isinstance(obj, SymbolTable...
AttributeError
dataset/ETHPy150Open xraypy/xraylarch/lib/wxlib/larchfilling.py/FillingTree.objGetChildren
5,843
def get_installed(method_filter=None): if method_filter is None: method_filter = ["max-product", 'ad3', 'qpbo', 'ogm', 'lp'] installed = [] unary = np.zeros((1, 1)) pw = np.zeros((1, 1)) edges = np.empty((0, 2), dtype=np.int) for method in method_filter: try: inferen...
ImportError
dataset/ETHPy150Open pystruct/pystruct/pystruct/inference/inference_methods.py/get_installed
5,844
def get_extractor(coarse, fine): log.debug("getting coarse extractor for '{}'".format(coarse)) # http://stackoverflow.com/questions/301134/dynamic-module-import-in-python try: coarse_extractor = importlib.import_module(__package__+'.'+question_types[coarse]) except (ImportError, __HOLE__): ...
KeyError
dataset/ETHPy150Open jcelliott/inquire/inquire/extraction/extractors.py/get_extractor
5,845
def parse_graminit_h(self, filename): """Parse the .h file written by pgen. (Internal) This file is a sequence of #define statements defining the nonterminals of the grammar as numbers. We build two tables mapping the numbers to names and back. """ try: f ...
IOError
dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/lib2to3/pgen2/conv.py/Converter.parse_graminit_h
5,846
def parse_graminit_c(self, filename): """Parse the .c file written by pgen. (Internal) The file looks as follows. The first two lines are always this: #include "pgenheaders.h" #include "grammar.h" After that come four blocks: 1) one or more state definitions ...
IOError
dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/lib2to3/pgen2/conv.py/Converter.parse_graminit_c
5,847
def unexpose(self, name): """Removes an exposed method @param name: (string) @return None """ #check the method dictionary first if name in self.exposedMethods: del self.exposedMethods[name] info = None #locally scoped try: #make sure t...
StopIteration
dataset/ETHPy150Open OrbitzWorldwide/droned/droned/lib/droned/models/action.py/AdminAction.unexpose
5,848
@classmethod def parse_ansi_colors(cls, source): # note: strips all control sequences, even if not SGRs. colors = [] plain = '' last = 0 curclr = 0 for match in ansi_seq.finditer(source): prevsegment = source[last:match.start()] plain += prevse...
ValueError
dataset/ETHPy150Open francelabs/datafari/cassandra/pylib/cqlshlib/test/ansi_colors.py/ColoredText.parse_ansi_colors
5,849
def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: from formadmin.forms import as_django_admin try: return as_django_admin(self) except __HOLE__: pass return super(UserSuForm, self).__str__()
ImportError
dataset/ETHPy150Open adamcharnock/django-su/django_su/forms.py/UserSuForm.__str__
5,850
def parse_revision_spec(self, revisions=[]): """Parses the given revision spec. The 'revisions' argument is a list of revisions as specified by the user. Items in the list do not necessarily represent a single revision, since the user can use SCM-native syntaxes such as "r1..r2" or "r1:...
ValueError
dataset/ETHPy150Open reviewboard/rbtools/rbtools/clients/svn.py/SVNClient.parse_revision_spec
5,851
def _convert_symbolic_revision(self, revision): command = ['-r', six.text_type(revision), '-l', '1'] if getattr(self.options, 'repository_url', None): command.append(self.options.repository_url) log = self.svn_log_xml(command) if log is not None: try: ...
ValueError
dataset/ETHPy150Open reviewboard/rbtools/rbtools/clients/svn.py/SVNClient._convert_symbolic_revision
5,852
def history_scheduled_with_commit(self, changelist, include_files, exclude_patterns): """ Method to find if any file status has '+' in 4th column""" status_cmd = ['status', '-q', '--ignore-externals'] if changelist: status_cmd.extend(['--changel...
IndexError
dataset/ETHPy150Open reviewboard/rbtools/rbtools/clients/svn.py/SVNClient.history_scheduled_with_commit
5,853
def apply_patch(self, patch_file, base_path, base_dir, p=None, revert=False): """Apply the patch and return a PatchResult indicating its success.""" if not is_valid_version(self.subversion_client_version, self.PATCH_MIN_VERSION): raise Mini...
IOError
dataset/ETHPy150Open reviewboard/rbtools/rbtools/clients/svn.py/SVNClient.apply_patch
5,854
def trim_dict( data, max_dict_bytes, percent=50.0, stepper_size=10, replace_with='VALUE_TRIMMED', is_msgpacked=False, use_bin_type=False): ''' Takes a dictionary and iterates over its keys, looking for large values and replacing them with a trimmed str...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/utils/dicttrim.py/trim_dict
5,855
def update_raid_info(node, raid_config): """Update the node's information based on the RAID config. This method updates the node's information to make use of the configured RAID for scheduling purposes (through properties['capabilities'] and properties['local_gb']) and deploying purposes (using pro...
KeyError
dataset/ETHPy150Open openstack/ironic/ironic/common/raid.py/update_raid_info
5,856
def get_job_url( self, str_job_name ): try: job_dict = self.get_job_dict() return job_dict[ str_job_name ] except __HOLE__: #noinspection PyUnboundLocalVariable all_views = ", ".join( job_dict.keys() ) raise KeyError("Job %s is not known - avai...
KeyError
dataset/ETHPy150Open ramonvanalteren/jenkinsapi/jenkinsapi/view.py/View.get_job_url
5,857
@property def docusign_parser(self): """Parser for DocuSign's request. This is a shortcut property using a cache. If you want to adapt the implementation, consider overriding :meth:`get_docusign_parser`. """ try: return self._docusign_parser exce...
AttributeError
dataset/ETHPy150Open novafloss/django-docusign/django_docusign/views.py/SignatureCallbackView.docusign_parser
5,858
@property def signature(self): """Signature model instance. This is a shortcut property using a cache. If you want to adapt the implementation, consider overriding :meth:`get_signature`. """ try: return self._signature except __HOLE__: ...
AttributeError
dataset/ETHPy150Open novafloss/django-docusign/django_docusign/views.py/SignatureCallbackView.signature
5,859
@property def signature_backend(self): """Signature backend instance. This is a shortcut property using a cache. If you want to adapt the implementation, consider overriding :meth:`get_signature_backend`. """ try: return self._signature_backend e...
AttributeError
dataset/ETHPy150Open novafloss/django-docusign/django_docusign/views.py/SignatureCallbackView.signature_backend
5,860
@webapi_check_local_site @webapi_login_required @webapi_response_errors(DOES_NOT_EXIST, INVALID_FORM_DATA, NOT_LOGGED_IN, PERMISSION_DENIED, TOKEN_GENERATION_FAILED) @webapi_request_fields( required={ 'note': { 'type': six.text_type, ...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/api_token.py/APITokenResource.create
5,861
@webapi_check_local_site @webapi_login_required @webapi_response_errors(DOES_NOT_EXIST, INVALID_FORM_DATA, NOT_LOGGED_IN, PERMISSION_DENIED) @webapi_request_fields( optional={ 'note': { 'type': six.text_type, 'description': 'The...
ValidationError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/api_token.py/APITokenResource.update
5,862
def detect_location_info(): """Detect location information.""" success = None for source in DATA_SOURCE: try: raw_info = requests.get(source, timeout=5).json() success = source break except (requests.RequestException, __HOLE__): success = Fals...
ValueError
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/util/location.py/detect_location_info
5,863
def elevation(latitude, longitude): """Return elevation for given latitude and longitude.""" req = requests.get(ELEVATION_URL, params={ 'locations': '{},{}'.format(latitude, longitude), 'sensor': 'false', }) if req.status_code != 200: return 0 try: return int(float(...
KeyError
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/util/location.py/elevation
5,864
def get(tree, name): """ Return a float value attribute NAME from TREE. """ if name in tree: value = tree[name] else: return float("nan") try: a = float(value) except __HOLE__: a = float("nan") return a
ValueError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/utils/toilStats.py/get
5,865
def getStats(options): """ Collect and return the stats and config data. """ def aggregateStats(fileHandle,aggregateObject): try: stats = json.load(fileHandle, object_hook=Expando) for key in stats.keys(): if key in aggregateObject: aggrega...
ValueError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/utils/toilStats.py/getStats
5,866
def processData(config, stats, options): ########################################## # Collate the stats and report ########################################## if stats.get("total_time", None) is None: # Hack to allow unfinished toils. stats.total_time = {"total_time": "0.0", "total_clock": "0.0"...
TypeError
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/utils/toilStats.py/processData
5,867
def touch(self, key, cost=None): """ Update score for key Provide a cost the first time and optionally thereafter. """ time = self._base if cost is not None: self.cost[key] = cost self.time[key] += self._base time = self.time[key] els...
KeyError
dataset/ETHPy150Open blaze/cachey/cachey/score.py/Scorer.touch
5,868
def _unpack_args(item_f, src_queue, link, args): if isinstance(item_f, FSQWorkItem): item_id = item_f.id src_queue = item_f.queue item_f = item_f.item elif src_queue: item_id = coerce_unicode(item_f, _c.FSQ_CHARSET) item_f = None else: args = list(args) ...
IndexError
dataset/ETHPy150Open axialmarket/fsq/fsq/enqueue.py/_unpack_args
5,869
def venqueue(trg_queue, item_f, args, user=None, group=None, mode=None): '''Enqueue the contents of a file, or file-like object, file-descriptor or the contents of a file at an address (e.g. '/my/file') queue with an argument list, venqueue is to enqueue what vprintf is to printf If entropy is...
IOError
dataset/ETHPy150Open axialmarket/fsq/fsq/enqueue.py/venqueue
5,870
def vreenqueue(item_f, *args, **kwargs): '''Enqueue the contents of a file, or file-like object, FSQWorkItem, file-descriptor or the contents of a files queues at an address (e.g. '/my/file') queue with arbitrary arguments from one queue to other queues, reenqueue is to vreenqueue what printf i...
OSError
dataset/ETHPy150Open axialmarket/fsq/fsq/enqueue.py/vreenqueue
5,871
def import_app(app_label, verbosity): # We get the app_path, necessary to use imp module find function try: app_path = __import__(app_label, {}, {}, [app_label.split('.')[-1]]).__path__ except AttributeError: return except __HOLE__: print "Unknown application: %s" % app_label ...
ImportError
dataset/ETHPy150Open maraujop/django-rules/django_rules/management/commands/sync_rules.py/import_app
5,872
def safeint(value): try: return int(value) except __HOLE__: return value
ValueError
dataset/ETHPy150Open ionelmc/django-redisboard/src/redisboard/views.py/safeint
5,873
def main(): """ Get the market cap! """ btc = Decimal(0) try: for balance in get_balances(): try: btc += get_amt_in_btc(balance) except ValueError: sys.stderr.write( 'WARNING: Cannot convert {0} to btc\n'.format( ...
HTTPError
dataset/ETHPy150Open robmcl4/Coinex/market_cap.py/main
5,874
def __hash__(self): try: return self._cached_hash except __HOLE__: h = self._cached_hash = hash(repr(self)) return h
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/predicates.py/Predicate.__hash__
5,875
def __call__(self, record) : column = record[self.field] if column : try : centers = self.index.search(self.preprocess(column), self.threshold) except __HOLE__ : raise AttributeError("Attempting to block...
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/predicates.py/TfidfSearchPredicate.__call__
5,876
def __call__(self, record) : block_key = None column = record[self.field] if column : doc = self.preprocess(column) try : doc_id = self.index._doc_to_id[doc] except __HOLE__ : raise AttributeError("Attempting to block with an...
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/predicates.py/TfidfCanopyPredicate.__call__
5,877
def existsPredicate(field) : try : if any(field) : return (u'1',) else : return (u'0',) except __HOLE__ : if field : return (u'1',) else : return (u'0',)
TypeError
dataset/ETHPy150Open datamade/dedupe/dedupe/predicates.py/existsPredicate
5,878
def __call__(self, fd, events): if not (events & ioloop.IOLoop.READ): if events == ioloop.IOLoop.ERROR: self.redirector.remove_fd(fd) return try: data = os.read(fd, self.redirector.buffer) if len(data) == 0: ...
IOError
dataset/ETHPy150Open circus-tent/circus/circus/stream/redirector.py/Redirector.Handler.__call__
5,879
@classmethod def _gen_memd_wrappers(cls, factory): """Generates wrappers for all the memcached operations. :param factory: A function to be called to return the wrapped method. It will be called with two arguments; the first is the unbound method being wrapped, and the second...
AttributeError
dataset/ETHPy150Open couchbase/couchbase-python-client/couchbase/bucket.py/Bucket._gen_memd_wrappers
5,880
def __init__(self, params): timeout = params.get('timeout', params.get('TIMEOUT', 300)) try: timeout = int(timeout) except (__HOLE__, TypeError): timeout = 300 self.default_timeout = timeout options = params.get('OPTIONS', {}) max_entries = params...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/cache/backends/base.py/BaseCache.__init__
5,881
def clean(self, value): if value: try: map(int, value) except (TypeError, __HOLE__): raise ValidationError('You must enter valid integer values.') return '-'.join(value)
ValueError
dataset/ETHPy150Open disqus/gargoyle/gargoyle/conditions.py/Range.clean
5,882
def clean(self, value): try: date = self.str_to_date(value) except __HOLE__, e: raise ValidationError("Date must be a valid date in the format YYYY-MM-DD.\n(%s)" % e.message) return date.strftime(self.DATE_FORMAT)
ValueError
dataset/ETHPy150Open disqus/gargoyle/gargoyle/conditions.py/AbstractDate.clean
5,883
def describe(self, identifiers): if not identifiers: raise MissingParameterValue('', 'identifier') identifier_elements = [] # 'all' keyword means all processes if 'all' in (ident.lower() for ident in identifiers): for process in self.processes: tr...
KeyError
dataset/ETHPy150Open geopython/pywps/pywps/app/Service.py/Service.describe
5,884
def execute(self, identifier, wps_request, uuid): """Parse and perform Execute WPS request call :param identifier: process identifier string :param wps_request: pywps.WPSRequest structure with parsed inputs, still in memory :param uuid: string identifier of the request """ ...
KeyError
dataset/ETHPy150Open geopython/pywps/pywps/app/Service.py/Service.execute
5,885
def __init__(self, filename, sorted=False, header=False): if filename.endswith(".delta"): coordsfile = filename.rsplit(".", 1)[0] + ".coords" if need_update(filename, coordsfile): fromdelta([filename]) filename = coordsfile super(Coords, self).__init...
AssertionError
dataset/ETHPy150Open tanghaibao/jcvi/formats/coords.py/Coords.__init__
5,886
def coverage(args): """ %prog coverage coordsfile Report the coverage per query record, useful to see which query matches reference. The coords file MUST be filtered with supermap:: jcvi.algorithms.supermap --filter query """ p = OptionParser(coverage.__doc__) p.add_option("-c", dest=...
AssertionError
dataset/ETHPy150Open tanghaibao/jcvi/formats/coords.py/coverage
5,887
def annotate(args): """ %prog annotate coordsfile Annotate coordsfile to append an additional column, with the following overlaps: {0}. """ p = OptionParser(annotate.__doc__.format(", ".join(Overlap_types))) p.add_option("--maxhang", default=100, type="int", help="Max hang ...
AssertionError
dataset/ETHPy150Open tanghaibao/jcvi/formats/coords.py/annotate
5,888
def filter(args): """ %prog filter <deltafile|coordsfile> Produce a new delta/coords file and filter based on id% or cov%. Use `delta-filter` for .delta file. """ p = OptionParser(filter.__doc__) p.set_align(pctid=0, hitlen=0) p.add_option("--overlap", default=False, action="store_true"...
AssertionError
dataset/ETHPy150Open tanghaibao/jcvi/formats/coords.py/filter
5,889
@memoize def get_package(command): try: c = CommandNotFound.CommandNotFound() cmd = command.split(' ') pkgs = c.getPackages(cmd[0] if cmd[0] != 'sudo' else cmd[1]) name, _ = pkgs[0] return name except __HOLE__: # IndexError is thrown when no matching package is fo...
IndexError
dataset/ETHPy150Open nvbn/thefuck/thefuck/rules/apt_get.py/get_package
5,890
def create_archive(): ravello_dir = util.get_ravello_dir() try: st = os.stat(ravello_dir) except OSError: st = None if st and not stat.S_ISDIR(st.st_mode): error.raise_error("Path `{0}` exists but is not a directory.", ravello_dir) elif st is None: ...
OSError
dataset/ETHPy150Open ravello/testmill/lib/testmill/tasks.py/create_archive
5,891
def __init__(self, positions, end=None): """ Construct a Feature which may apply at C{positions}. #For instance, importing some concrete subclasses (Feature is abstract) >>> from nltk.tag.brill import Word, Pos #Feature Word, applying at one of [-2, -1] >>> Word([-2,-1]...
TypeError
dataset/ETHPy150Open nltk/nltk/nltk/tbl/feature.py/Feature.__init__
5,892
@staticmethod def load(response, encoding): response = response.decode(encoding) try: return json.loads(response) except __HOLE__: return response except json.decoder.JSONDecodeError: return response
ValueError
dataset/ETHPy150Open haikuginger/beekeeper/beekeeper/data_handlers.py/PlainText.load
5,893
def command(self, cmd, *args): func = getattr(self.__class__, cmd, False) # silently ignore nonsensical calls because the logger loops over each # writer and passes the command separately to all of them if func and func.__dict__.get('_callable', False): try: r...
TypeError
dataset/ETHPy150Open sassoftware/conary/conary/lib/logger.py/LogWriter.command
5,894
def close(self): """ Reassert control of tty. Closing stdin, stderr, and and stdout will get rid of the last pointer to the slave fd of the pseudo tty, which should cause the logging process to stop. We wait for it to die before continuing """ if not self.lo...
AttributeError
dataset/ETHPy150Open sassoftware/conary/conary/lib/logger.py/Logger.close
5,895
def _controlTerminal(self): try: # the child should control stdin -- if stdin is a tty # that can be controlled if sys.stdin.isatty(): os.tcsetpgrp(0, os.getpgrp()) except __HOLE__: # stdin might not even have an isatty method pa...
AttributeError
dataset/ETHPy150Open sassoftware/conary/conary/lib/logger.py/_ChildLogger._controlTerminal
5,896
def log(self): if self.shouldControlTerminal: self._controlTerminal() # standardize terminal size at 24, 80 for those programs that # access it. This should ensure that programs that look at # terminal size for displaying log info will look similar across # runs. ...
OSError
dataset/ETHPy150Open sassoftware/conary/conary/lib/logger.py/_ChildLogger.log
5,897
def process_image_diff(diff_path, before_path, after_path): cmd = ["perceptualdiff", "-output", diff_path, before_path, after_path] try: proc = subprocess.Popen(cmd) code = proc.wait() except __HOLE__: fail("Failed to run: %s" % " ".join(cmd)) sys.exit(1) return code
OSError
dataset/ETHPy150Open bokeh/bokeh/tests/plugins/image_diff.py/process_image_diff
5,898
def _update_extents(self): inp = self.plane.input extents = list(_get_extent(inp)) pos = self.position axis = self._get_axis_index() extents[2*axis] = pos extents[2*axis+1] = pos try: self.plane.set_extent(extents) except __HOLE__: ...
AttributeError
dataset/ETHPy150Open enthought/mayavi/mayavi/components/grid_plane.py/GridPlane._update_extents
5,899
def validateEmail(email): try: validate_email(email) return True except __HOLE__: return False
ValidationError
dataset/ETHPy150Open haystack/eyebrowse-server/common/view_helpers.py/validateEmail