Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
6,000
def has_builder(self): """Return whether this Node has a builder or not. In Boolean tests, this turns out to be a *lot* more efficient than simply examining the builder attribute directly ("if node.builder: ..."). When the builder attribute is examined directly, it ends up calling __getattr__ for both the __len__ and __nonzero__ attributes on instances of our Builder Proxy class(es), generating a bazillion extra calls and slowing things down immensely. """ try: b = self.builder except __HOLE__: # There was no explicit builder for this Node, so initialize # the self.builder attribute to None now. b = self.builder = None return b is not None
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.has_builder
6,001
def has_explicit_builder(self): """Return whether this Node has an explicit builder This allows an internal Builder created by SCons to be marked non-explicit, so that it can be overridden by an explicit builder that the user supplies (the canonical example being directories).""" try: return self.is_explicit except __HOLE__: self.is_explicit = None return self.is_explicit
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.has_explicit_builder
6,002
def get_builder(self, default_builder=None): """Return the set builder, or a specified default value""" try: return self.builder except __HOLE__: return default_builder
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_builder
6,003
def get_source_scanner(self, node): """Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations where this is already verified. This function may be called very often; it attempts to cache the scanner found to improve performance. """ scanner = None try: scanner = self.builder.source_scanner except __HOLE__: pass if not scanner: # The builder didn't have an explicit scanner, so go look up # a scanner from env['SCANNERS'] based on the node's scanner # key (usually the file extension). scanner = self.get_env_scanner(self.get_build_env()) if scanner: scanner = scanner.select(node) return scanner
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_source_scanner
6,004
def get_ninfo(self): try: return self.ninfo except __HOLE__: self.ninfo = self.new_ninfo() return self.ninfo
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_ninfo
6,005
def get_binfo(self): """ Fetch a node's build information. node - the node whose sources will be collected cache - alternate node to use for the signature cache returns - the build signature This no longer handles the recursive descent of the node's children's signatures. We expect that they're already built and updated by someone else, if that's what's wanted. """ try: return self.binfo except __HOLE__: pass binfo = self.new_binfo() self.binfo = binfo executor = self.get_executor() ignore_set = self.ignore_set if self.has_builder(): binfo.bact = str(executor) binfo.bactsig = SCons.Util.MD5signature(executor.get_contents()) if self._specific_sources: sources = [] for s in self.sources: if s not in ignore_set: sources.append(s) else: sources = executor.get_unignored_sources(self, self.ignore) seen = set() bsources = [] bsourcesigs = [] for s in sources: if not s in seen: seen.add(s) bsources.append(s) bsourcesigs.append(s.get_ninfo()) binfo.bsources = bsources binfo.bsourcesigs = bsourcesigs depends = self.depends dependsigs = [] for d in depends: if d not in ignore_set: dependsigs.append(d.get_ninfo()) binfo.bdepends = depends binfo.bdependsigs = dependsigs implicit = self.implicit or [] implicitsigs = [] for i in implicit: if i not in ignore_set: implicitsigs.append(i.get_ninfo()) binfo.bimplicit = implicit binfo.bimplicitsigs = implicitsigs return binfo
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_binfo
6,006
def del_binfo(self): """Delete the build info from this node.""" try: delattr(self, 'binfo') except __HOLE__: pass
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.del_binfo
6,007
def get_csig(self): try: return self.ninfo.csig except __HOLE__: ninfo = self.get_ninfo() ninfo.csig = SCons.Util.MD5signature(self.get_contents()) return self.ninfo.csig
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_csig
6,008
def add_dependency(self, depend): """Adds dependencies.""" try: self._add_child(self.depends, self.depends_set, depend) except __HOLE__, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
TypeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.add_dependency
6,009
def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) except __HOLE__, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
TypeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.add_ignore
6,010
def add_source(self, source): """Adds sources.""" if self._specific_sources: return try: self._add_child(self.sources, self.sources_set, source) except __HOLE__, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
TypeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.add_source
6,011
def _children_get(self): try: return self._memo['children_get'] except __HOLE__: pass # The return list may contain duplicate Nodes, especially in # source trees where there are a lot of repeated #includes # of a tangle of .h files. Profiling shows, however, that # eliminating the duplicates with a brute-force approach that # preserves the order (that is, something like: # # u = [] # for n in list: # if n not in u: # u.append(n)" # # takes more cycles than just letting the underlying methods # hand back cached values if a Node's information is requested # multiple times. (Other methods of removing duplicates, like # using dictionary keys, lose the order, and the only ordered # dictionary patterns I found all ended up using "not in" # internally anyway...) if self.ignore_set: iter = chain.from_iterable(filter(None, [self.sources, self.depends, self.implicit])) children = [] for i in iter: if i not in self.ignore_set: children.append(i) else: children = self.all_children(scan=0) self._memo['children_get'] = children return children
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node._children_get
6,012
def explain(self): if not self.exists(): return "building `%s' because it doesn't exist\n" % self if self.always_build: return "rebuilding `%s' because AlwaysBuild() is specified\n" % self old = self.get_stored_info() if old is None: return None old = old.binfo old.prepare_dependencies() try: old_bkids = old.bsources + old.bdepends + old.bimplicit old_bkidsigs = old.bsourcesigs + old.bdependsigs + old.bimplicitsigs except __HOLE__: return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self new = self.get_binfo() new_bkids = new.bsources + new.bdepends + new.bimplicit new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs osig = dict(zip(old_bkids, old_bkidsigs)) nsig = dict(zip(new_bkids, new_bkidsigs)) # The sources and dependencies we'll want to report are all stored # as relative paths to this target's directory, but we want to # report them relative to the top-level SConstruct directory, # so we only print them after running them through this lambda # to turn them into the right relative Node and then return # its string. def stringify( s, E=self.dir.Entry ) : if hasattr( s, 'dir' ) : return str(E(s)) return str(s) lines = [] removed = [x for x in old_bkids if not x in new_bkids] if removed: removed = list(map(stringify, removed)) fmt = "`%s' is no longer a dependency\n" lines.extend([fmt % s for s in removed]) for k in new_bkids: if not k in old_bkids: lines.append("`%s' is a new dependency\n" % stringify(k)) elif k.changed_since_last_build(self, osig[k]): lines.append("`%s' changed\n" % stringify(k)) if len(lines) == 0 and old_bkids != new_bkids: lines.append("the dependency order changed:\n" + "%sold: %s\n" % (' '*15, list(map(stringify, old_bkids))) + "%snew: %s\n" % (' '*15, list(map(stringify, new_bkids)))) if len(lines) == 0: def fmt_with_title(title, strlines): lines = strlines.split('\n') sep = '\n' + ' '*(15 + len(title)) return ' '*15 + title + sep.join(lines) + '\n' if old.bactsig != new.bactsig: if old.bact == new.bact: lines.append("the contents of the build action changed\n" + fmt_with_title('action: ', new.bact)) else: lines.append("the build action changed:\n" + fmt_with_title('old: ', old.bact) + fmt_with_title('new: ', new.bact)) if len(lines) == 0: return "rebuilding `%s' for unknown reasons\n" % self preamble = "rebuilding `%s' because" % self if len(lines) == 1: return "%s %s" % (preamble, lines[0]) else: lines = ["%s:\n" % preamble] + lines return ( ' '*11).join(lines)
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.explain
6,013
def post(self): """POST""" ca_id = self.request.get('ca_id', None) auth1 = self.GetAuth1Instance(ca_id=ca_id) if self._IsRemoteIpAddressBlocked(os.environ.get('REMOTE_ADDR', '')): raise base.NotAuthenticated('RemoteIpAddressBlocked') n = self.request.get('n', None) m = self.request.get('m', None) s = self.request.get('s', None) # uncomment for verbose logging on input auth sesssions #logging.debug('Input n=%s m=%s s=%s', n, m, s) try: auth1.Input(n=n, m=m, s=s) except __HOLE__, e: logging.exception('invalid parameters to auth1.Input()') raise base.NotAuthenticated('InvalidAuth1InputParams') output = auth1.Output() auth_state = auth1.AuthState() if auth_state == gaeserver.base.AuthState.OK: if output: self.response.headers['Set-Cookie'] = '%s=%s; secure; httponly;' % ( auth.AUTH_TOKEN_COOKIE, output) self.response.out.write(auth.AUTH_TOKEN_COOKIE) else: logging.critical('Auth is OK but there is no output.') raise base.NotAuthenticated('AuthOkOutputEmpty') elif auth_state == gaeserver.base.AuthState.FAIL: raise base.NotAuthenticated('AuthStateFail') elif output: self.response.out.write(output) else: logging.critical('auth_state is %s but no output.', auth_state) # technically 500, 403 for security raise base.NotAuthenticated('AuthStateUnknownOutputEmpty')
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/munki/handlers/auth.py/Auth.post
6,014
def create(vm_): ''' Create a single instance from a data dict. CLI Examples: .. code-block:: bash salt-cloud -p qingcloud-ubuntu-c1m1 hostname1 salt-cloud -m /path/to/mymap.sls -P ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'qingcloud', vm_['profile'], vm_=vm_) is False: return False except __HOLE__: pass # Since using "provider: <provider-engine>" is deprecated, alias provider # to use driver: "driver: <provider-engine>" if 'provider' in vm_: vm_['driver'] = vm_.pop('provider') salt.utils.cloud.fire_event( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), { 'name': vm_['name'], 'profile': vm_['profile'], 'provider': vm_['driver'], }, transport=__opts__['transport'] ) log.info('Creating Cloud VM {0}'.format(vm_['name'])) # params params = { 'action': 'RunInstances', 'instance_name': vm_['name'], 'zone': _get_location(vm_), 'instance_type': _get_size(vm_), 'image_id': _get_image(vm_), 'vxnets.1': vm_['vxnets'], 'login_mode': vm_['login_mode'], 'login_keypair': vm_['login_keypair'], } salt.utils.cloud.fire_event( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), {'kwargs': params}, transport=__opts__['transport'] ) result = query(params) new_instance_id = result['instances'][0] try: data = salt.utils.cloud.wait_for_ip( _query_node_data, update_args=(new_instance_id,), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60 ), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10 ), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(str(exc)) private_ip = data['private_ips'][0] log.debug('VM {0} is now running'.format(private_ip)) vm_['ssh_host'] = private_ip # The instance is booted and accessible, let's Salt it! salt.utils.cloud.bootstrap(vm_, __opts__) log.info('Created Cloud VM \'{0[name]}\''.format(vm_)) log.debug( '\'{0[name]}\' VM creation details:\n{1}'.format( vm_, pprint.pformat(data) ) ) salt.utils.cloud.fire_event( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), { 'name': vm_['name'], 'profile': vm_['profile'], 'provider': vm_['driver'], }, transport=__opts__['transport'] ) return data
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/qingcloud.py/create
6,015
def create(self, req, body): """Creates a new snapshot.""" context = req.environ['nova.context'] authorize(context, action='create') if not self.is_valid_body(body, 'snapshot'): raise webob.exc.HTTPBadRequest() try: snapshot = body['snapshot'] create_info = snapshot['create_info'] volume_id = snapshot['volume_id'] except __HOLE__: raise webob.exc.HTTPBadRequest() LOG.info(_LI("Create assisted snapshot from volume %s"), volume_id, context=context) return self.compute_api.volume_snapshot_create(context, volume_id, create_info)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/assisted_volume_snapshots.py/AssistedVolumeSnapshotsController.create
6,016
def delete(self, req, id): """Delete a snapshot.""" context = req.environ['nova.context'] authorize(context, action='delete') LOG.info(_LI("Delete snapshot with id: %s"), id, context=context) delete_metadata = {} delete_metadata.update(req.GET) try: delete_info = jsonutils.loads(delete_metadata['delete_info']) volume_id = delete_info['volume_id'] except (KeyError, __HOLE__) as e: raise webob.exc.HTTPBadRequest(explanation=six.text_type(e)) try: self.compute_api.volume_snapshot_delete(context, volume_id, id, delete_info) except exception.NotFound: return webob.exc.HTTPNotFound() return webob.Response(status_int=204)
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/assisted_volume_snapshots.py/AssistedVolumeSnapshotsController.delete
6,017
def __init__(self, name, start=False, profile_sql=False, connection_names=('default',)): """Constructor :param name: name of the Profiler instance :type name: string :param start: whether to start immediately after Profiler instantiation :type start: bool :param profile_sql: whether to profile sql queries or not :type profile_sql: bool :param connection_names: names of database connections to profile :type connection_names: tuple :returns: Profiler instance :rtype: profiling.Profiler """ if settings is not None and hasattr(settings, 'PROFILING_LOGGER_NAME'): logger_name = settings.PROFILING_LOGGER_NAME else: logger_name = __name__ if name.find(' ') == -1: logger_name += '.{0}'.format(name) self.log = logging.getLogger(logger_name) self.name = name self.pre_queries_cnt = {} self.profile_sql = profile_sql try: assert isinstance(connection_names, tuple) self.connection_names = connection_names except __HOLE__: self.connection_names = 'default', if start: self.start()
AssertionError
dataset/ETHPy150Open CodeScaleInc/django-profiler/profiling/__init__.py/Profiler.__init__
6,018
def profile(*fn, **options): """Decorator for profiling functions and class methods. :param profile_sql: whether to profile sql queries or not :type profile_sql: bool :param stats: whether to use cProfile or profile module to get execution statistics :type stats: bool :param stats_filename: filename where stats generated data are dumped :type stats_filename: str :param stats_buffer: how to display execution statistics, defaultly put into logging :type stats_buffer: file-like object with write method :returns: wrapped function object :rtype: types.FunctionType :raises: TypeError, IOError """ profile_sql = options.pop('profile_sql', False) stats = options.pop('stats', False) stats_filename = options.pop('stats_filename', None) stats_buffer = options.pop('stats_buffer', None) if options: raise TypeError('Unsupported keyword arguments: %s' % ','.join(options.keys())) def decorator(func): try: func.__name__ except AttributeError: # This decorator is on top of another decorator implemented as class func.__name__ = func.__class__.__name__ try: functools.update_wrapper(decorator, func) except __HOLE__: pass def wrapper(*args, **kwargs): try: functools.update_wrapper(wrapper, func) except AttributeError: pass if (args and hasattr(args[0], '__class__') and args[0].__class__.__dict__.get(func.__name__) is not None and args[0].__class__.__dict__.get(func.__name__).__name__ == func.__name__): profiler_name = '%s.%s' % (args[0].__class__.__name__, func.__name__) else: if hasattr(func, '__name__'): profiler_name = '{0}.{1}'.format(func.__module__, func.__name__) elif hasattr(func, '__class__'): profiler_name = func.__class__.__name__ else: profiler_name = 'Profiler' if stats: prof = profile_module.Profile() with Profiler(profiler_name, profile_sql=profile_sql): to_return = prof.runcall(func, *args, **kwargs) old_stdout = sys.stdout sys.stdout = StringIO() prof.print_stats() statistics = sys.stdout.getvalue() sys.stdout.close() sys.stdout = old_stdout if stats_buffer is not None: stats_buffer.write(statistics) else: logger_name = settings.PROFILING_LOGGER_NAME if settings is not None and hasattr(settings, 'PROFILING_LOGGER_NAME') else __name__ logging.getLogger('{0}.{1}'.format(logger_name, profiler_name)).info(statistics) if stats_filename is not None: prof.dump_stats(stats_filename) else: with Profiler(profiler_name, profile_sql=profile_sql): to_return = func(*args, **kwargs) return to_return try: return functools.update_wrapper(wrapper, func) except AttributeError: return wrapper if fn and inspect.isfunction(fn[0]): # Called with no parameter return decorator(fn[0]) else: # Called with a parameter return decorator
AttributeError
dataset/ETHPy150Open CodeScaleInc/django-profiler/profiling/__init__.py/profile
6,019
def validate_maplight_date(d): try: datetime.strptime(d, '%Y-%m-%d') return True except __HOLE__: return False # TODO Also create MapLightContestMeasure
ValueError
dataset/ETHPy150Open wevoteeducation/WeVoteBase/import_export_maplight/models.py/validate_maplight_date
6,020
@click.command(short_help="Upload datasets to Mapbox accounts") @click.argument('tileset', required=True) @click.argument('infile', type=click.File('r'), required=False) @click.option('--name', default=None, help="Name for the data upload") @click.pass_context def upload(ctx, tileset, infile, name): """Upload data to Mapbox accounts. All endpoints require authentication. Uploaded data lands at https://www.mapbox.com/data/ and can be used in new or existing projects. $ mapbox upload username.data data.geojson Note that the tileset must start with your username. An access token with upload scope is required, see `mapbox --help`. """ access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Uploader(access_token=access_token) try: res = service.upload(infile, tileset, name) except (mapbox.errors.ValidationError, __HOLE__) as exc: raise click.BadParameter(str(exc)) if res.status_code == 201: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
IOError
dataset/ETHPy150Open mapbox/mapbox-cli-py/mapboxcli/scripts/uploads.py/upload
6,021
def match(self, regexp, flags=None): """compile the given regexp, cache the reg, and call match_reg().""" try: reg = _regexp_cache[(regexp, flags)] except __HOLE__: if flags: reg = re.compile(regexp, flags) else: reg = re.compile(regexp) _regexp_cache[(regexp, flags)] = reg return self.match_reg(reg)
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lexer.py/Lexer.match
6,022
def decode_raw_stream(self, text, decode_raw, known_encoding, filename): """given string/unicode or bytes/string, determine encoding from magic encoding comment, return body as unicode or raw if decode_raw=False """ if isinstance(text, compat.text_type): m = self._coding_re.match(text) encoding = m and m.group(1) or known_encoding or 'ascii' return encoding, text if text.startswith(codecs.BOM_UTF8): text = text[len(codecs.BOM_UTF8):] parsed_encoding = 'utf-8' m = self._coding_re.match(text.decode('utf-8', 'ignore')) if m is not None and m.group(1) != 'utf-8': raise exceptions.CompileException( "Found utf-8 BOM in file, with conflicting " "magic encoding comment of '%s'" % m.group(1), text.decode('utf-8', 'ignore'), 0, 0, filename) else: m = self._coding_re.match(text.decode('utf-8', 'ignore')) if m: parsed_encoding = m.group(1) else: parsed_encoding = known_encoding or 'ascii' if decode_raw: try: text = text.decode(parsed_encoding) except __HOLE__: raise exceptions.CompileException( "Unicode decode operation of encoding '%s' failed" % parsed_encoding, text.decode('utf-8', 'ignore'), 0, 0, filename) return parsed_encoding, text
UnicodeDecodeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lexer.py/Lexer.decode_raw_stream
6,023
def has_object_permission(self, permission, request, view, obj): safe_locals = {"obj": obj, "request": request} try: attr1_value = eval(self.obj_attr1, {}, safe_locals) attr2_value = eval(self.obj_attr2, {}, safe_locals) except __HOLE__: return False else: return attr1_value == attr2_value
AttributeError
dataset/ETHPy150Open niwinz/djangorestframework-composed-permissions/restfw_composed_permissions/generic/components.py/ObjectAttrEqualToObjectAttr.has_object_permission
6,024
def getPositionByType(self, tagSet): if not self.__tagToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 tagMap = self.__namedTypes[idx].getType().getTagMap() for t in tagMap.getPosMap(): if t in self.__tagToPosIdx: raise error.PyAsn1Error('Duplicate type %s' % (t,)) self.__tagToPosIdx[t] = idx try: return self.__tagToPosIdx[tagSet] except __HOLE__: raise error.PyAsn1Error('Type %s not found' % (tagSet,))
KeyError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/pyasn1/type/namedtype.py/NamedTypes.getPositionByType
6,025
def getNameByPosition(self, idx): try: return self.__namedTypes[idx].getName() except __HOLE__: raise error.PyAsn1Error('Type position out of range')
IndexError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/pyasn1/type/namedtype.py/NamedTypes.getNameByPosition
6,026
def getPositionByName(self, name): if not self.__nameToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 n = self.__namedTypes[idx].getName() if n in self.__nameToPosIdx: raise error.PyAsn1Error('Duplicate name %s' % (n,)) self.__nameToPosIdx[n] = idx try: return self.__nameToPosIdx[name] except __HOLE__: raise error.PyAsn1Error('Name %s not found' % (name,))
KeyError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/pyasn1/type/namedtype.py/NamedTypes.getPositionByName
6,027
def getTagMapNearPosition(self, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return self.__ambigiousTypes[idx].getTagMap() except __HOLE__: raise error.PyAsn1Error('Type position out of range')
KeyError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/pyasn1/type/namedtype.py/NamedTypes.getTagMapNearPosition
6,028
def getPositionNearType(self, tagSet, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return idx+self.__ambigiousTypes[idx].getPositionByType(tagSet) except __HOLE__: raise error.PyAsn1Error('Type position out of range')
KeyError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/pyasn1/type/namedtype.py/NamedTypes.getPositionNearType
6,029
def compress(self, data_list): if data_list: try: month = int(data_list[0]) except (ValueError, __HOLE__): raise forms.ValidationError(self.error_messages['invalid_month']) try: year = int(data_list[1]) except (ValueError, TypeError): raise forms.ValidationError(self.error_messages['invalid_year']) try: day = monthrange(year, month)[1] # last day of the month except IllegalMonthError: raise forms.ValidationError(self.error_messages['invalid_month']) except ValueError: raise forms.ValidationError(self.error_messages['invalid_year']) return date(year, month, day) return None
TypeError
dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/etc/credit_card_fields.py/ExpiryDateField.compress
6,030
def test_errors_non_list(): """ When a ListField is given a non-list value, then there should be one error related to the type mismatch. """ field = ListField(child=DateField()) try: field.to_internal_value('notAList') assert False, 'Expected ValidationError' except __HOLE__ as e: pass
ValidationError
dataset/ETHPy150Open estebistec/drf-compound-fields/tests/test_listfield.py/test_errors_non_list
6,031
def test_validate_elements_valid(): """ When a ListField is given a list whose elements are valid for the item-field, then validate should not raise a ValidationError. """ field = ListField(child=CharField(max_length=5)) try: field.to_internal_value(["a", "b", "c"]) except __HOLE__: assert False, "ValidationError was raised"
ValidationError
dataset/ETHPy150Open estebistec/drf-compound-fields/tests/test_listfield.py/test_validate_elements_valid
6,032
def perform_search(fn_to_tagged_sents, onset=None, nucleus=None, coda=None, tone=None, initial=None, final=None, jyutping=None, character=None, pos=None, word_range=(0, 0), sent_range=(0, 0), tagged=True, sents=False): """ overall strategy: deal with jp (and all jp-related elements) first, and then the character 1. jp hierarchy of jp and associated search elements: jp / | \ onset/initial final tone / \ nucleus coda lower search elements cannot be used together with dominating higher elements """ # ensure tuple type: word_range and sent_range if not (type(word_range) == type(sent_range) == tuple): raise ValueError('word_range and sent_range must be tuples') words_left, words_right = word_range sents_left, sents_right = sent_range # ensure int type: words_left, words_right, sents_left, sents_right if not (type(words_left) == type(words_right) == type(sents_left) == type(sents_right) == int): raise ValueError('int required for {words, sents}_{left, right}') if sents_left > 0 or sents_right > 0: sents = True # determine what kinds of search we are doing character_search = False jp_search = False pos_search = False if character: character_search = True if onset or nucleus or coda or tone or final or jyutping: jp_search = True if pos: pos_search = True if not (character_search or jp_search or pos_search): raise ValueError('no search elements') # check if jyutping search is valid jp_search_tuple = (None, None, None, None) if jp_search: # ensure compatible jyutping search elements if final and (nucleus or coda): raise ValueError('final cannot be used together with ' 'either nucleus or coda (or both)') if jyutping and (onset or final or nucleus or coda or tone): raise ValueError('jyutping cannot be used together with other ' 'Jyutping elements') if (onset != initial) and onset and initial: raise ValueError('onset conflicts with initial') # onset/initial if initial: onset = initial # determine jp_search_tuple if jyutping: try: jp_search_list = parse_jyutping(jyutping) except ValueError: raise ValueError('invalid jyutping -- %s' % (repr(jyutping))) if len(jp_search_list) > 1: raise ValueError('only jyutping for one character is allowed') else: jp_search_tuple = jp_search_list[0] else: if final: nucleus, coda = parse_final(final) jp_search_tuple = (onset, nucleus, coda, tone) fn_to_results = dict() for fn, tagged_sents in fn_to_tagged_sents.items(): sent_word_index_pairs = list() for i_sent, tagged_sent in enumerate(tagged_sents): for i_word, tagged_word in enumerate(tagged_sent): c_characters, c_pos, c_mor, _ = tagged_word # c = current c_jyutping = get_jyutping_from_mor(c_mor) # determine character_search and pos_search if character_search: character_match = character in c_characters else: character_match = True if pos_search: pos_match = re.fullmatch(pos, c_pos) else: pos_match = True if not (character_match and pos_match): continue # determine if jyutping matches c_jyutping jyutping_match = False if not jp_search and not c_jyutping: jyutping_match = True elif not c_jyutping: pass else: try: c_parsed_jyutpings = parse_jyutping(c_jyutping) except __HOLE__: continue for c_parsed_jyutping in c_parsed_jyutpings: booleans = [_jp_element_match(search_, current_) for search_, current_ in zip(jp_search_tuple, c_parsed_jyutping)] if all(booleans): jyutping_match = True break if jyutping_match: sent_word_index_pairs.append((i_sent, i_word)) results_list = list() for i_sent, i_word in sent_word_index_pairs: if not sents: tagged_sent = tagged_sents[i_sent] i_word_start = i_word - words_left i_word_end = i_word + words_right + 1 if i_word_start < 0: i_word_start = 0 if i_word_end > len(tagged_sent): i_word_end = len(tagged_sent) words_wanted = tagged_sent[i_word_start: i_word_end] if not tagged: words_wanted = [x[0] for x in words_wanted] if len(words_wanted) == 1: words_wanted = words_wanted[0] results_list.append(words_wanted) else: i_sent_start = i_sent - sents_left i_sent_end = i_sent + sents_right + 1 if i_sent_start < 0: i_sent_start = 0 if i_sent_end > len(tagged_sents): i_sent_end = len(tagged_sents) sents_wanted = tagged_sents[i_sent_start: i_sent_end] if not tagged: for i, sent in enumerate(sents_wanted[:]): sents_wanted[i] = [x[0] for x in sent] if len(sents_wanted) == 1: sents_wanted = sents_wanted[0] results_list.append(sents_wanted) fn_to_results[fn] = results_list return fn_to_results
ValueError
dataset/ETHPy150Open pycantonese/pycantonese/pycantonese/search.py/perform_search
6,033
def run(self, test): "Run the given test case or test suite." result = self._makeResult() registerResult(result) result.failfast = self.failfast result.buffer = self.buffer with warnings.catch_warnings(): if self.warnings: # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ['default', 'always']: warnings.filterwarnings('module', category=DeprecationWarning, message='Please use assert\w+ instead.') startTime = time.time() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() try: test(result) finally: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() stopTime = time.time() timeTaken = stopTime - startTime result.printErrors() if hasattr(result, 'separator2'): self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() expectedFails = unexpectedSuccesses = skipped = 0 try: results = map(len, (result.expectedFailures, result.unexpectedSuccesses, result.skipped)) except __HOLE__: pass else: expectedFails, unexpectedSuccesses, skipped = results infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") failed, errored = len(result.failures), len(result.errors) if failed: infos.append("failures=%d" % failed) if errored: infos.append("errors=%d" % errored) else: self.stream.write("OK") if skipped: infos.append("skipped=%d" % skipped) if expectedFails: infos.append("expected failures=%d" % expectedFails) if unexpectedSuccesses: infos.append("unexpected successes=%d" % unexpectedSuccesses) if infos: self.stream.writeln(" (%s)" % (", ".join(infos),)) else: self.stream.write("\n") return result
AttributeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/runner.py/TextTestRunner.run
6,034
def _weigh_object(self, host_state, weight_properties): value = 0.0 # NOTE(sbauza): Keying a dict of Metrics per metric name given that we # have a MonitorMetricList object metrics_dict = {m.name: m for m in host_state.metrics or []} for (name, ratio) in self.setting: try: value += metrics_dict[name].value * ratio except __HOLE__: if CONF.metrics.required: raise exception.ComputeHostMetricNotFound( host=host_state.host, node=host_state.nodename, name=name) else: # We treat the unavailable metric as the most negative # factor, i.e. set the value to make this obj would be # at the end of the ordered weighed obj list # Do nothing if ratio or weight_multiplier is 0. if ratio * self.weight_multiplier() != 0: return CONF.metrics.weight_of_unavailable return value
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/scheduler/weights/metrics.py/MetricsWeigher._weigh_object
6,035
def render(self, context): # Try to resolve the variables. If they are not resolve-able, then use # the provided name itself. try: email = self.email.resolve(context) except template.VariableDoesNotExist: email = self.email.var try: rating = self.rating.resolve(context) except template.VariableDoesNotExist: rating = self.rating.var try: size = self.size.resolve(context) except template.VariableDoesNotExist: size = self.size.var except __HOLE__: size = self.size try: default = self.default.resolve(context) except template.VariableDoesNotExist: default = self.default.var gravatargs = { 'hash': md5.new(email).hexdigest(), 'rating': rating, 'size': size, 'default': urllib.quote_plus(default), } url = GRAVATAR_URL % gravatargs if 'as' in self.other_kwargs: context[self.other_kwargs['as']] = mark_safe(url) return '' return url
AttributeError
dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/gravatar.py/GravatarUrlNode.render
6,036
def render(self, name, value, attrs): encoded = value if not is_password_usable(encoded): return "None" final_attrs = self.build_attrs(attrs) encoded = smart_str(encoded) if len(encoded) == 32 and '$' not in encoded: algorithm = 'unsalted_md5' else: algorithm = encoded.split('$', 1)[0] try: hasher = get_hasher(algorithm) except __HOLE__: summary = "<strong>Invalid password format or unknown hashing algorithm.</strong>" else: summary = "" for key, value in hasher.safe_summary(encoded).iteritems(): summary += "<strong>%(key)s</strong>: %(value)s " % {"key": ugettext(key), "value": value} return mark_safe("<div%(attrs)s>%(summary)s</div>" % {"attrs": flatatt(final_attrs), "summary": summary})
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/auth/forms.py/ReadOnlyPasswordHashWidget.render
6,037
def render(self, context): try: expire_time = self.expire_time_var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var) try: expire_time = int(expire_time) except (__HOLE__, TypeError): raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time) if self.cache_name: try: cache_name = self.cache_name.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.cache_name.var) try: fragment_cache = caches[cache_name] except InvalidCacheBackendError: raise TemplateSyntaxError('Invalid cache name specified for cache tag: %r' % cache_name) else: try: fragment_cache = caches['template_fragments'] except InvalidCacheBackendError: fragment_cache = caches['default'] vary_on = [var.resolve(context) for var in self.vary_on] cache_key = make_template_fragment_key(self.fragment_name, vary_on) value = fragment_cache.get(cache_key) if value is None: value = self.nodelist.render(context) fragment_cache.set(cache_key, value, expire_time) return value
ValueError
dataset/ETHPy150Open django/django/django/templatetags/cache.py/CacheNode.render
6,038
def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key set with an object from a different database try: marty.book_set = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to an m2m with an object from a different database try: marty.book_set.add(dive) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Set a m2m with an object from a different database try: marty.book_set = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a reverse m2m with an object from a different database try: dive.authors.add(marty) self.fail("Shouldn't be able to assign across databases") except __HOLE__: pass # Set a reverse m2m with an object from a different database try: dive.authors = [mark, marty] self.fail("Shouldn't be able to assign across databases") except ValueError: pass
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/QueryTestCase.test_m2m_cross_database_protection
6,039
def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key with an object from a different database try: dive.editor = marty self.fail("Shouldn't be able to assign across databases") except __HOLE__: pass # Set a foreign key set with an object from a different database try: marty.edited = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a foreign key set with an object from a different database try: marty.edited.add(dive) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. chris = Person(name="Chris Mills") html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) # initially, no db assigned self.assertEqual(chris._state.db, None) self.assertEqual(html5._state.db, None) # old object comes from 'other', so the new object is set to use 'other'... dive.editor = chris html5.editor = mark self.assertEqual(chris._state.db, 'other') self.assertEqual(html5._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)), [u'Mark Pilgrim']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into Python']) # When saved (no using required), new objects goes to 'other' chris.save() html5.save() self.assertEqual(list(Person.objects.using('default').values_list('name',flat=True)), [u'Marty Alchin']) self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)), [u'Chris Mills', u'Mark Pilgrim']) self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python']) # This also works if you assign the FK in the constructor water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark) self.assertEqual(water._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python']) # When saved, the new book goes to 'other' water.save() self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python', u'Dive into Water'])
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/QueryTestCase.test_foreign_key_cross_database_protection
6,040
def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager('default').create_user('alice', '[email protected]') # Create a user and profile on the other database bob = User.objects.db_manager('other').create_user('bob', '[email protected]') # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile self.fail("Shouldn't be able to assign across databases") except __HOLE__: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog') new_bob_profile = UserProfile(flavor="spring surprise") charlie = User(username='charlie',email='[email protected]') charlie.set_unusable_password() # initially, no db assigned self.assertEqual(new_bob_profile._state.db, None) self.assertEqual(charlie._state.db, None) # old object comes from 'other', so the new object is set to use 'other'... new_bob_profile.user = bob charlie.userprofile = bob_profile self.assertEqual(new_bob_profile._state.db, 'other') self.assertEqual(charlie._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)), [u'bob']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog']) # When saved (no using required), new objects goes to 'other' charlie.save() bob_profile.save() new_bob_profile.save() self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)), [u'alice']) self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)), [u'bob', u'charlie']) self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise']) # This also works if you assign the O2O relation in the constructor denise = User.objects.db_manager('other').create_user('denise','[email protected]') denise_profile = UserProfile(flavor="tofu", user=denise) self.assertEqual(denise_profile._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise']) # When saved, the new profile goes to 'other' denise_profile.save() self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise', u'tofu'])
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/QueryTestCase.test_o2o_cross_database_protection
6,041
def test_generic_key_cross_database_protection(self): "Operations that involve sharing generic key objects across databases raise an error" copy_content_types_from_default_to_other() # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) # Set a foreign key with an object from a different database try: review1.content_object = dive self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a foreign key set with an object from a different database try: dive.reviews.add(review1) self.fail("Shouldn't be able to assign across databases") except __HOLE__: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertEqual(review3._state.db, None) # Dive comes from 'other', so review3 is set to use 'other'... review3.content_object = dive self.assertEqual(review3._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), [u'Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)), [u'Python Weekly']) # When saved, John goes to 'other' review3.save() self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), [u'Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)), [u'Python Daily', u'Python Weekly'])
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/QueryTestCase.test_generic_key_cross_database_protection
6,042
def test_subquery(self): """Make sure as_sql works with subqueries and master/slave.""" sub = Person.objects.using('other').filter(name='fff') qs = Book.objects.filter(editor__in=sub) # When you call __str__ on the query object, it doesn't know about using # so it falls back to the default. If the subquery explicitly uses a # different database, an error should be raised. self.assertRaises(ValueError, str, qs.query) # Evaluating the query shouldn't work, either try: for obj in qs: pass self.fail('Iterating over query should raise ValueError') except __HOLE__: pass
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/QueryTestCase.test_subquery
6,043
def test_foreign_key_cross_database_protection(self): "Foreign keys can cross databases if they two databases have a common source" # Create a book and author on the default database pro = Book.objects.using('default').create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.using('default').create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key with an object from a different database try: dive.editor = marty except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Set a foreign key set with an object from a different database try: marty.edited = [pro, dive] except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Assignment implies a save, so database assignments of original objects have changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'default') self.assertEqual(mark._state.db, 'other') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Add to a foreign key set with an object from a different database try: marty.edited.add(dive) except __HOLE__: self.fail("Assignment across master/slave databases with a common source should be ok") # Add implies a save, so database assignments of original objects have changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'default') self.assertEqual(mark._state.db, 'other') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') # If you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. chris = Person(name="Chris Mills") html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) # initially, no db assigned self.assertEqual(chris._state.db, None) self.assertEqual(html5._state.db, None) # old object comes from 'other', so the new object is set to use the # source of 'other'... self.assertEqual(dive._state.db, 'other') dive.editor = chris html5.editor = mark self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') self.assertEqual(chris._state.db, 'default') self.assertEqual(html5._state.db, 'default') # This also works if you assign the FK in the constructor water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark) self.assertEqual(water._state.db, 'default') # For the remainder of this test, create a copy of 'mark' in the # 'default' database to prevent integrity errors on backends that # don't defer constraints checks until the end of the transaction mark.save(using='default') # This moved 'mark' in the 'default' database, move it back in 'other' mark.save(using='other') self.assertEqual(mark._state.db, 'other') # If you create an object through a FK relation, it will be # written to the write database, even if the original object # was on the read database cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15)) self.assertEqual(cheesecake._state.db, 'default') # Same goes for get_or_create, regardless of whether getting or creating cheesecake, created = mark.edited.get_or_create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15)) self.assertEqual(cheesecake._state.db, 'default') puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15)) self.assertEqual(puddles._state.db, 'default')
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/RouterTestCase.test_foreign_key_cross_database_protection
6,044
def test_m2m_cross_database_protection(self): "M2M relations can cross databases if the database share a source" # Create books and authors on the inverse to the usual database pro = Book.objects.using('other').create(pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") dive = Book.objects.using('default').create(pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim") # Now save back onto the usual database. # This simulates master/slave - the objects exist on both database, # but the _state.db is as it is for all other tests. pro.save(using='default') marty.save(using='default') dive.save(using='other') mark.save(using='other') # Check that we have 2 of both types of object on both databases self.assertEqual(Book.objects.using('default').count(), 2) self.assertEqual(Book.objects.using('other').count(), 2) self.assertEqual(Person.objects.using('default').count(), 2) self.assertEqual(Person.objects.using('other').count(), 2) # Set a m2m set with an object from a different database try: marty.book_set = [pro, dive] except __HOLE__: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 2) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() # Add to an m2m with an object from a different database try: marty.book_set.add(dive) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() # Set a reverse m2m with an object from a different database try: dive.authors = [mark, marty] except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 2) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() self.assertEqual(Book.authors.through.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Add to a reverse m2m with an object from a different database try: dive.authors.add(marty) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database alice = dive.authors.create(name='Alice') self.assertEqual(alice._state.db, 'default') # Same goes for get_or_create, regardless of whether getting or creating alice, created = dive.authors.get_or_create(name='Alice') self.assertEqual(alice._state.db, 'default') bob, created = dive.authors.get_or_create(name='Bob') self.assertEqual(bob._state.db, 'default')
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/RouterTestCase.test_m2m_cross_database_protection
6,045
def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager('default').create_user('alice', '[email protected]') # Create a user and profile on the other database bob = User.objects.db_manager('other').create_user('bob', '[email protected]') # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile except __HOLE__: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(alice._state.db, 'default') self.assertEqual(alice_profile._state.db, 'default') self.assertEqual(bob._state.db, 'other') # ... but they will when the affected object is saved. bob.save() self.assertEqual(bob._state.db, 'default')
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/RouterTestCase.test_o2o_cross_database_protection
6,046
def test_generic_key_cross_database_protection(self): "Generic Key operations can span databases if they share a source" copy_content_types_from_default_to_other() # Create a book and author on the default database pro = Book.objects.using('default' ).create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.using('default' ).create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using('other' ).create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other' ).create(source="Python Weekly", content_object=dive) # Set a generic foreign key with an object from a different database try: review1.content_object = dive except __HOLE__: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, 'default') self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(review2._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Add to a generic foreign key set with an object from a different database try: dive.reviews.add(review1) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, 'default') self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(review2._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertEqual(review3._state.db, None) # Dive comes from 'other', so review3 is set to use the source of 'other'... review3.content_object = dive self.assertEqual(review3._state.db, 'default') # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database dive = Book.objects.using('other').get(title='Dive into Python') nyt = dive.reviews.create(source="New York Times", content_object=dive) self.assertEqual(nyt._state.db, 'default')
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/multiple_database/tests.py/RouterTestCase.test_generic_key_cross_database_protection
6,047
@property def currentWindow(self): try: return self.focusHistory[-1] except __HOLE__: # no window has focus return None
IndexError
dataset/ETHPy150Open qtile/qtile/libqtile/group.py/_Group.currentWindow
6,048
@currentWindow.setter def currentWindow(self, win): try: self.focusHistory.remove(win) except __HOLE__: # win has never received focus before pass self.focusHistory.append(win)
ValueError
dataset/ETHPy150Open qtile/qtile/libqtile/group.py/_Group.currentWindow
6,049
def _remove_from_focus_history(self, win): try: index = self.focusHistory.index(win) except __HOLE__: # win has never received focus return False else: del self.focusHistory[index] # return True if win was the last item (i.e. it was currentWindow) return index == len(self.focusHistory)
ValueError
dataset/ETHPy150Open qtile/qtile/libqtile/group.py/_Group._remove_from_focus_history
6,050
def assert_equal_steps(test_case, expected, actual): """ Assert that the list of provided steps are the same. If they are not, display the differences intelligently. :param test_case: The ``TestCase`` whose assert methods will be called. :param expected: The expected build step instance. :param actual: The actual build step instance. :raises: ``TestFailure`` if the build steps are not equal, showing the unequal or missing steps. """ expected_steps = getattr(expected, 'steps') actual_steps = getattr(actual, 'steps') if None in (expected_steps, actual_steps): test_case.assertEqual(expected, actual) else: mismatch_steps = [] missing_steps = [] index = 0 for index, expected_step in enumerate(expected_steps): try: actual_step = actual_steps[index] except __HOLE__: missing_steps = expected_steps[index:] break if expected_step != actual_step: mismatch_steps.append( '* expected: {} !=\n' ' actual: {}'.format( expected_step, actual_step)) extra_steps = actual_steps[index+1:] if mismatch_steps or missing_steps or extra_steps: test_case.fail( 'Step Mismatch\n' 'Mismatch:\n{}\n' 'Missing:\n{}\n' 'Extra:\n{}'.format( '\n'.join(mismatch_steps), missing_steps, extra_steps) )
IndexError
dataset/ETHPy150Open ClusterHQ/flocker/admin/test/test_packaging.py/assert_equal_steps
6,051
def test_internal_symlinks_only(self): """ The resulting ``virtualenv`` only contains symlinks to files inside the virtualenv and to /usr on the host OS. """ target_path = FilePath(self.mktemp()) create_virtualenv(root=target_path) allowed_targets = (target_path, FilePath('/usr'),) bad_links = [] for path in target_path.walk(): if path.islink(): realpath = path.realpath() for allowed_target in allowed_targets: try: realpath.segmentsFrom(allowed_target) except __HOLE__: pass else: # The target is a descendent of an allowed_target. break else: bad_links.append(path) if bad_links: self.fail( "Symlinks outside of virtualenv detected:" + '\n'.join( '/'.join( path.segmentsFrom(target_path) ) + ' -> ' + path.realpath().path for path in bad_links ) )
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/admin/test/test_packaging.py/CreateVirtualenvTests.test_internal_symlinks_only
6,052
def test_usage_error_message(self): """ ``DockerBuildScript.main`` prints a usage error to ``stderr`` if there are missing command line options. """ fake_sys_module = FakeSysModule(argv=[]) script = DockerBuildScript(sys_module=fake_sys_module) try: script.main() except __HOLE__: pass self.assertEqual( 'Wrong number of arguments.', fake_sys_module.stderr.getvalue().splitlines()[-1] )
SystemExit
dataset/ETHPy150Open ClusterHQ/flocker/admin/test/test_packaging.py/DockerBuildScriptTests.test_usage_error_message
6,053
def test_usage_error_message(self): """ ``BuildScript.main`` prints a usage error to ``stderr`` if there are missing command line options. """ fake_sys_module = FakeSysModule(argv=[]) script = BuildScript(sys_module=fake_sys_module) try: script.main(top_level=FLOCKER_PATH) except __HOLE__: pass self.assertEqual( 'Wrong number of arguments.', fake_sys_module.stderr.getvalue().splitlines()[-1] )
SystemExit
dataset/ETHPy150Open ClusterHQ/flocker/admin/test/test_packaging.py/BuildScriptTests.test_usage_error_message
6,054
def parseStringToPythonAst(text): lineOffsets = computeLineOffsets(text) try: pyAst = astCache_.get(text) if pyAst is None: pyAst = astCache_[text] = convertPythonAstToForaPythonAst(ast.parse(text), lineOffsets) return pyAst except SyntaxError as e: return ForaNative.PythonParseError(e.msg, e.filename, e.lineno, e.offset, e.text) except __HOLE__ as e: return ForaNative.PythonParseError(str(e.message))
TypeError
dataset/ETHPy150Open ufora/ufora/ufora/FORA/python/PurePython/PythonAstConverter.py/parseStringToPythonAst
6,055
def last_event(request, slug): "Displays a list of all services and their current status." try: service = Service.objects.get(slug=slug) except Service.DoesNotExist: return HttpResponseRedirect(reverse('overseer:index')) try: evt = service.event_set.order_by('-date_created')[0] except __HOLE__: return HttpResponseRedirect(service.get_absolute_url()) return event(request, evt.pk)
IndexError
dataset/ETHPy150Open disqus/overseer/overseer/views.py/last_event
6,056
def test_drop_column(self): try: self.tbl.drop_column('date') assert 'date' not in self.tbl.columns except __HOLE__: pass
NotImplementedError
dataset/ETHPy150Open pudo/dataset/test/test_persistence.py/TableTestCase.test_drop_column
6,057
def hamming(str1, str2): """Algorithm based on an old project of mine, ported from yavascript: christabor.github.io/etude/09-02-2014/. A superior algorithm exists at wikipedia.org/wiki/Hamming_distance#Algorithm_example, but copying it would defeat the purpose.""" dist = 0 last_longer = len(str1) < len(str2) first, last = (str1, str2,) if last_longer else (str2, str1,) for k, letter in enumerate(str1): try: if str1[k] != str2[k]: dist += 1 except __HOLE__: continue # Add remainder between offset of each (e.g. "cat", "cats" = range(2, 3)) for k in range(len(first), len(last)): dist += 1 print('Hamming dist for `{}` and `{}` = {}'.format(str1, str2, dist)) return dist
IndexError
dataset/ETHPy150Open christabor/MoAL/MOAL/algorithms/coding_theory/hamming_distance.py/hamming
6,058
def state_writer(self): while self.server.is_alive(): # state is not guaranteed accurate, as we do not # update the file on every iteration gevent.sleep(0.01) try: job_id, job = self.server.first_job() except __HOLE__: self.update_state(None, None) continue self.update_state(job_id, job)
IndexError
dataset/ETHPy150Open dcramer/taskmaster/src/taskmaster/server.py/Controller.state_writer
6,059
@staticmethod def json_body(req): if not req.content_length: return {} try: raw_json = req.stream.read() except Exception: raise freezer_api_exc.BadDataFormat('Empty request body. A valid ' 'JSON document is required.') try: json_data = json.loads(raw_json, 'utf-8') except __HOLE__: raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON') return json_data
ValueError
dataset/ETHPy150Open openstack/freezer-api/freezer_api/api/common/resource.py/BaseResource.json_body
6,060
@opt.register_specialize @opt.register_stabilize @opt.register_canonicalize @gof.local_optimizer([CrossentropySoftmax1HotWithBiasDx]) def local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc(node): """ Replace a CrossentropySoftmax1HotWithBiasDx op, whose incoming gradient is an `alloc` of a scalar variable or one that has either broadcastable or matching dimensions with the output variable, by one that skips the intermediate `alloc`. """ if isinstance(node.op, CrossentropySoftmax1HotWithBiasDx): dy, sm, y_idx = node.inputs # Those cases are directly handled by the internal broadcasting of the # `CrossentropySoftmax1HotWithBiasDx` op. if dy.ndim == 0: return False if dy.ndim == 1 and dy.broadcastable[0]: return False assert dy.ndim == 1 if dy.owner is not None and isinstance(dy.owner.op, tensor.Alloc): # dz is the input of the Alloc op, i.e. T.alloc(dz, <shape>) dz = dy.owner.inputs[0] try: shape_feature = node.fgraph.shape_feature except __HOLE__: # The shape feature may not be available in some mode, but we # need it for this optimization, so don't continue. return False shape_of = shape_feature.shape_of same_shape = shape_feature.same_shape # Build `dz_broad` explicitly to include extra implicit dimensions. dz_broad = (True,) * (dy.ndim - dz.ndim) + dz.broadcastable # If we can infer statically that the shape of `sm` and # `dy` are the same in dimension `k` or the shape of `dy` is equal # to 1 (which triggers the internal broadcasting in # `CrossentropySoftmax1HotWithBiasDx`) we do not need to # check it at runtime. if (dz_broad[0] and not same_shape(sm, dy, dim_x=0, dim_y=0) and shape_of[dy][0] != 1): # If `dz` is broadcastable, we need to check whether the shapes # of `dy` and `sm` are the same or whether the shape of `dy` is # equal to 1. cond = tensor.or_(tensor.eq(dy.shape[0], 1), tensor.eq(dy.shape[0], sm.shape[0])) msg = '`sm` and `dy` do not have the same shape.' dz = opt.Assert(msg)(dz, cond) ret = node.op(dz, sm, y_idx) copy_stack_trace(node.outputs[0], ret) return [ret]
AttributeError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tensor/nnet/nnet.py/local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc
6,061
def gerbers_to_svg(manufacturer='default'): """ Takes Gerber files as input and generates an SVG of them """ def normalise_gerber_number(gerber_number, axis, form): """ Takes a Gerber number and converts it into a float using the formatting defined in the Gerber header """ # TODO: actually support anything other than leading zeros number = gerber_number / pow(10.0, form[axis]['decimal']) return number def parsed_grammar_to_dict(parsed_grammar): """ Converts the Gerber parsing results to an SVG. """ gerber_dict = {} current_aperture = None new_shape = True for line in parsed_grammar: if line.dump(): if (line.format): if gerber_dict.get('format') is None: gerber_dict['format'] = {} tmp = gerber_dict['format'] tmp['notation'] = line['format']['notation'] tmp['zeros'] = line['format']['zeros'] tmp['x'] = {} tmp['x']['integer'] = line['format']['x']['integer'] tmp['x']['decimal'] = line['format']['x']['decimal'] tmp['y'] = {} tmp['y']['integer'] = line['format']['x']['integer'] tmp['y']['decimal'] = line['format']['x']['decimal'] elif (line.units): gerber_dict['units'] = line['units']['units'] elif (line.aperture_definition): tmp = {} if line['aperture_definition']['type'] == 'circle': tmp['type'] = 'circle' tmp['diameter'] = line['aperture_definition']['diameter'] tmp['number'] = line['aperture_definition']['number'] elif line['aperture_definition']['type'] == 'rect': tmp['type'] = 'rect' tmp['width'] = line['aperture_definition']['width'] tmp['height'] = line['aperture_definition']['height'] tmp['number'] = line['aperture_definition']['number'] else: print("ERROR: cannot recognise aperture definition type") if gerber_dict.get('aperture-definitions') is None: gerber_dict['aperture-definitions'] = [] gerber_dict['aperture-definitions'].append(tmp) elif line.polarity_change: if gerber_dict.get('features') is None: gerber_dict['features'] = [] polarity = line['polarity_change']['polarity'] polarity_dict = {} polarity_dict['polarity'] = polarity polarity_dict['shapes'] = [] gerber_dict['features'].append(polarity_dict) elif line.aperture_change: tmp = {} tmp['type'] = 'aperture-change' tmp['number'] = line.aperture_change['number'] #if len(gerber_dict['features'][-1]['shapes'] == 0): gerber_dict['features'][-1]['shapes'].append(tmp) #else: # gerber_dict['features'][-1]['shapes'].append(tmp) tmp = {} tmp['type'] = 'stroke' tmp['segments'] = [] gerber_dict['features'][-1]['shapes'].append(tmp) elif line.start_closed_shape: tmp = {} tmp['type'] = 'fill' tmp['segments'] = [] gerber_dict['features'][-1]['shapes'].append(tmp) elif line.move or line.draw or line.flash: # TODO: hack alert! (Got to get shit done, you know? Don't judge me!) if line.move: command_name = 'move' item = line.move if line.draw: command_name = 'draw' item = line.draw if line.flash: command_name = 'flash' item = line.flash point = Point(normalise_gerber_number(item['x'], 'x', gerber_dict['format']), normalise_gerber_number(item['y'], 'y', gerber_dict['format'])) tmp = {} tmp['type'] = command_name tmp['coord'] = point gerber_dict['features'][-1]['shapes'][-1]['segments'].append(tmp) elif line.end_closed_shape: new_shape = True return gerber_dict def create_gerber_svg_data(gerber_data): """ Returns an SVG element of the input Gerber data """ gerber_data_parsed = gerber_grammar.parseString(gerber_data) gerber_data_dict = parsed_grammar_to_dict(gerber_data_parsed) gerber_data_svg = svg.generate_svg_from_gerber_dict(gerber_data_dict) return gerber_data_svg # get the board's shape / outline board_shape_gerber_lp = None shape = config.brd['board_outline']['shape'] board_shape_type = shape.get('type') if board_shape_type in ['rect', 'rectangle']: offset = utils.to_Point(shape.get('offset') or [0, 0]) board_shape_path = svg.rect_to_path(shape) elif board_shape_type == 'path': board_shape_path = shape.get('value') board_shape_gerber_lp = shape.get('gerber_lp') if board_shape_path is None: print("ERROR: couldn't find a path under key 'value' for board outline") else: print("ERROR: unrecognised board shape type: %s. Possible options are 'rect' or 'path'" % board_shape_type) # convert path to relative board_shape_path_relative = svg.absolute_to_relative_path(board_shape_path) # this will return a path having an origin at the center of the shape # defined by the path board_width, board_height, board_outline = svg.transform_path(board_shape_path_relative, True) display_width = board_width display_height = board_height #transform = 'translate(' + str(round((board_width)/2, SD)) + ' ' + str(round((board_height)/2, SD)) + ')' sig_dig = config.cfg['significant-digits'] #transform = 'translate(%s %s)' % (round(board_width/2, sig_dig), # round(board_height/2, sig_dig)) # extra buffer for display frame display_frame_buffer = config.cfg.get('display-frame-buffer') or 1.0 gerber = et.Element('svg', width=str(display_width) + config.brd['config']['units'], height=str(display_height) + config.brd['config']['units'], viewBox=str(-display_frame_buffer/2) + ' ' + str(-display_frame_buffer/2) + ' ' + str(board_width+display_frame_buffer) + ' ' + str(board_height + display_frame_buffer), version='1.1', nsmap=cfg['namespace'], fill='black') doc = et.ElementTree(gerber) gerber_layers = svg.create_layers_for_gerber_svg(gerber) # directory for where to expect the Gerbers within the build path # regardless of the source of the Gerbers, the PCBmodE directory # structure is assumed production_path = os.path.join(config.cfg['base-dir'], config.cfg['locations']['build'], 'production') # get board information from configuration file pcbmode_version = config.cfg['version'] board_name = config.cfg['name'] board_revision = config.brd['config'].get('rev') base_name = "%s_rev_%s" % (board_name, board_revision) gerber_grammar = gerber_grammar_generator() for foil in ['outline']:#, 'documentation']: gerber_file = os.path.join(production_path, base_name + '_%s.ger'% (foil)) gerber_data = open(gerber_file, 'r').read() gerber_svg = create_gerber_svg_data(gerber_data) gerber_svg_layer = gerber_layers[foil]['layer'] gerber_svg_layer.append(gerber_svg) print(foil) #for pcb_layer in utils.getSurfaceLayers(): for pcb_layer in config.stk['layer-names']: for foil in ['conductor', 'silkscreen', 'soldermask']: gerber_file = os.path.join(production_path, base_name + '_%s_%s.ger'% (pcb_layer, foil)) gerber_data = open(gerber_file, 'r').read() gerber_svg = create_gerber_svg_data(gerber_data) gerber_svg_layer = gerber_layers[pcb_layer][foil]['layer'] gerber_svg_layer.append(gerber_svg) print(foil) output_file = os.path.join(config.cfg['base-dir'], config.cfg['locations']['build'], cfg['board_name'] + '_gerber.svg') try: f = open(output_file, 'wb') except __HOLE__ as e: print("I/O error({0}): {1}".format(e.errno, e.strerror)) f.write(et.tostring(doc, pretty_print=True)) f.close() return
IOError
dataset/ETHPy150Open boldport/pcbmode/pcbmode/utils/gerber.py/gerbers_to_svg
6,062
@classmethod def PushNotification(cls, client, user_id, alert, badge, callback, exclude_device_id=None, extra=None, sound=None): """Queries all devices for 'user'. Devices with 'push_token' set are pushed notifications via the push_notification API. NOTE: currently, code path is synchronous, but the callback is provided in case that changes. If specified, 'exclude_device_id' will exclude a particular device from the set to which notifications are pushed. For example, the device which is querying notifications when the badge is set to 0. """ def _OnQuery(devices): with util.Barrier(callback) as b: now = util.GetCurrentTimestamp() for device in devices: if device.device_id != exclude_device_id: token = device.push_token assert token, device try: PushNotification.Push(token, alert=alert, badge=badge, sound=sound, extra=extra) except __HOLE__ as e: logging.error('bad push token %s', token) Device._HandleBadPushToken(client, token, time.time(), b.Callback()) except Exception as e: logging.warning('failed to push notification to user %d: %s', user_id, e) raise # Find all devices owned by the user that need to be alerted. Device.QueryAlertable(client, user_id, _OnQuery)
TypeError
dataset/ETHPy150Open viewfinderco/viewfinder/backend/db/device.py/Device.PushNotification
6,063
def eval_evec(symmetric, d, typ, k, which, v0=None, sigma=None, mattype=np.asarray, OPpart=None, mode='normal'): general = ('bmat' in d) if symmetric: eigs_func = eigsh else: eigs_func = eigs if general: err = ("error for %s:general, typ=%s, which=%s, sigma=%s, " "mattype=%s, OPpart=%s, mode=%s" % (eigs_func.__name__, typ, which, sigma, mattype.__name__, OPpart, mode)) else: err = ("error for %s:standard, typ=%s, which=%s, sigma=%s, " "mattype=%s, OPpart=%s, mode=%s" % (eigs_func.__name__, typ, which, sigma, mattype.__name__, OPpart, mode)) a = d['mat'].astype(typ) ac = mattype(a) if general: b = d['bmat'].astype(typ.lower()) bc = mattype(b) # get exact eigenvalues exact_eval = d['eval'].astype(typ.upper()) ind = argsort_which(exact_eval, typ, k, which, sigma, OPpart, mode) exact_eval = exact_eval[ind] # compute arpack eigenvalues kwargs = dict(which=which, v0=v0, sigma=sigma) if eigs_func is eigsh: kwargs['mode'] = mode else: kwargs['OPpart'] = OPpart # compute suitable tolerances kwargs['tol'], rtol, atol = _get_test_tolerance(typ, mattype) # on rare occasions, ARPACK routines return results that are proper # eigenvalues and -vectors, but not necessarily the ones requested in # the parameter which. This is inherent to the Krylov methods, and # should not be treated as a failure. If such a rare situation # occurs, the calculation is tried again (but at most a few times). ntries = 0 while ntries < 5: # solve if general: try: eval, evec = eigs_func(ac, k, bc, **kwargs) except ArpackNoConvergence: kwargs['maxiter'] = 20*a.shape[0] eval, evec = eigs_func(ac, k, bc, **kwargs) else: try: eval, evec = eigs_func(ac, k, **kwargs) except ArpackNoConvergence: kwargs['maxiter'] = 20*a.shape[0] eval, evec = eigs_func(ac, k, **kwargs) ind = argsort_which(eval, typ, k, which, sigma, OPpart, mode) eval = eval[ind] evec = evec[:,ind] # check eigenvectors LHS = np.dot(a, evec) if general: RHS = eval * np.dot(b, evec) else: RHS = eval * evec assert_allclose(LHS, RHS, rtol=rtol, atol=atol, err_msg=err) try: # check eigenvalues assert_allclose_cc(eval, exact_eval, rtol=rtol, atol=atol, err_msg=err) break except __HOLE__: ntries += 1 # check eigenvalues assert_allclose_cc(eval, exact_eval, rtol=rtol, atol=atol, err_msg=err)
AssertionError
dataset/ETHPy150Open scipy/scipy/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py/eval_evec
6,064
@contextlib.contextmanager def cd(newpath): """ Change the current working directory to `newpath`, temporarily. If the old current working directory no longer exists, do not return back. """ oldpath = os.getcwd() os.chdir(newpath) try: yield finally: try: os.chdir(oldpath) except __HOLE__: # If oldpath no longer exists, stay where we are. pass # Check Sphinx version
OSError
dataset/ETHPy150Open networkx/networkx/doc/source/conf.py/cd
6,065
def DatabaseDirectorySize(root_path, extension): """Compute size (in bytes) and number of files of a file-based data store.""" directories = collections.deque([root_path]) total_size = 0 total_files = 0 while directories: directory = directories.popleft() try: items = os.listdir(directory) except OSError: continue for comp in items: if comp == constants.REBALANCE_DIRECTORY: continue path = os.path.join(directory, comp) try: statinfo = os.lstat(path) if stat.S_ISLNK(statinfo.st_mode): continue if stat.S_ISDIR(statinfo.st_mode): directories.append(path) elif stat.S_ISREG(statinfo.st_mode): if comp.endswith(extension): total_size += statinfo.st_size total_files += 1 except __HOLE__: continue return total_size, total_files
OSError
dataset/ETHPy150Open google/grr/grr/lib/data_stores/common.py/DatabaseDirectorySize
6,066
def _make_model_class(message_type, indexed_fields, **props): """Construct a Model subclass corresponding to a Message subclass. Args: message_type: A Message subclass. indexed_fields: A list of dotted and undotted field names. **props: Additional properties with which to seed the class. Returns: A Model subclass whose properties correspond to those fields of message_type whose field name is listed in indexed_fields, plus the properties specified by the **props arguments. For dotted field names, a StructuredProperty is generated using a Model subclass created by a recursive call. Raises: Whatever _analyze_indexed_fields() raises. ValueError if a field name conflicts with a name in **props. ValueError if a field name is not valid field of message_type. ValueError if an undotted field name designates a MessageField. """ analyzed = _analyze_indexed_fields(indexed_fields) for field_name, sub_fields in analyzed.iteritems(): if field_name in props: raise ValueError('field name %s is reserved' % field_name) try: field = message_type.field_by_name(field_name) except __HOLE__: raise ValueError('Message type %s has no field named %s' % (message_type.__name__, field_name)) if isinstance(field, messages.MessageField): if not sub_fields: raise ValueError( 'MessageField %s cannot be indexed, only sub-fields' % field_name) sub_model_class = _make_model_class(field.type, sub_fields) prop = model.StructuredProperty(sub_model_class, field_name, repeated=field.repeated) else: if sub_fields is not None: raise ValueError( 'Unstructured field %s cannot have indexed sub-fields' % field_name) if isinstance(field, messages.EnumField): prop = EnumProperty(field.type, field_name, repeated=field.repeated) elif isinstance(field, messages.BytesField): prop = model.BlobProperty(field_name, repeated=field.repeated, indexed=True) else: # IntegerField, FloatField, BooleanField, StringField. prop = model.GenericProperty(field_name, repeated=field.repeated) props[field_name] = prop return model.MetaModel('_%s__Model' % message_type.__name__, (model.Model,), props)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/ndb/msgprop.py/_make_model_class
6,067
def roundFact(fact, inferDecimals=False, vDecimal=None): if vDecimal is None: vStr = fact.value try: vDecimal = decimal.Decimal(vStr) vFloatFact = float(vStr) except (decimal.InvalidOperation, __HOLE__): # would have been a schema error reported earlier vDecimal = NaN vFloatFact = floatNaN else: #only vFloat is defined, may not need vStr unless inferring precision from decimals if vDecimal.is_nan(): return vDecimal vStr = None try: vFloatFact = float(fact.value) except ValueError: vFloatFact = floatNaN dStr = fact.decimals pStr = fact.precision if dStr == "INF" or pStr == "INF": vRounded = vDecimal elif inferDecimals: #infer decimals, round per 4.6.7.2, e.g., half-down if pStr: p = int(pStr) if p == 0: vRounded = NaN elif vDecimal == 0: vRounded = ZERO else: vAbs = fabs(vFloatFact) d = p - int(floor(log10(vAbs))) - 1 # defeat binary rounding to nearest even #if trunc(fmod(vFloat * (10 ** d),2)) != 0: # vFloat += 10 ** (-d - 1) * (1.0 if vFloat > 0 else -1.0) #vRounded = round(vFloat, d) vRounded = decimalRound(vDecimal,d,decimal.ROUND_HALF_EVEN) elif dStr: d = int(dStr) # defeat binary rounding to nearest even #if trunc(fmod(vFloat * (10 ** d),2)) != 0: # vFloat += 10 ** (-d - 1) * (-1.0 if vFloat > 0 else 1.0) #vRounded = round(vFloat, d) #vRounded = round(vFloat,d) vRounded = decimalRound(vDecimal,d,decimal.ROUND_HALF_EVEN) else: # no information available to do rounding (other errors xbrl.4.6.3 error) vRounded = vDecimal else: # infer precision if dStr: match = numberPattern.match(vStr if vStr else str(vDecimal)) if match: nonZeroInt, period, zeroDec, nonZeroDec, e, exp = match.groups() p = (len(nonZeroInt) if nonZeroInt and (len(nonZeroInt)) > 0 else -len(zeroDec)) + \ (int(exp) if exp and (len(exp) > 0) else 0) + \ (int(dStr)) else: p = 0 elif pStr: p = int(pStr) else: # no rounding information p = None if p == 0: vRounded = NaN elif vDecimal == 0: vRounded = vDecimal elif p is not None: # round per 4.6.7.1, half-up vAbs = vDecimal.copy_abs() log = vAbs.log10() # defeat rounding to nearest even d = p - int(log) - (1 if vAbs >= 1 else 0) #if trunc(fmod(vFloat * (10 ** d),2)) != 0: # vFloat += 10 ** (-d - 1) * (1.0 if vFloat > 0 else -1.0) #vRounded = round(vFloat, d) vRounded = decimalRound(vDecimal,d,decimal.ROUND_HALF_UP) else: # no information available to do rounding (other errors xbrl.4.6.3 error) vRounded = vDecimal return vRounded
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateXbrlCalcs.py/roundFact
6,068
def inferredPrecision(fact): vStr = fact.value dStr = fact.decimals pStr = fact.precision if dStr == "INF" or pStr == "INF": return floatINF try: vFloat = float(vStr) if dStr: match = numberPattern.match(vStr if vStr else str(vFloat)) if match: nonZeroInt, period, zeroDec, nonZeroDec, e, exp = match.groups() p = (len(nonZeroInt) if nonZeroInt else (-len(zeroDec) if nonZeroDec else 0)) + \ (int(exp) if exp else 0) + \ (int(dStr)) if p < 0: p = 0 # "pathological case" 2.1 spec example 13 line 7 else: p = 0 else: return int(pStr) except __HOLE__: return floatNaN if p == 0: return 0 elif vFloat == 0: return 0 else: return p
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateXbrlCalcs.py/inferredPrecision
6,069
def inferredDecimals(fact): vStr = fact.value dStr = fact.decimals pStr = fact.precision if dStr == "INF" or pStr == "INF": return floatINF try: if pStr: p = int(pStr) if p == 0: return floatNaN # =0 cannot be determined vFloat = float(vStr) if vFloat == 0: return floatINF # =0 cannot be determined else: vAbs = fabs(vFloat) return p - int(floor(log10(vAbs))) - 1 elif dStr: return int(dStr) except __HOLE__: pass return floatNaN
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateXbrlCalcs.py/inferredDecimals
6,070
def roundValue(value, precision=None, decimals=None, scale=None): try: vDecimal = decimal.Decimal(value) if scale: iScale = int(scale) vDecimal = vDecimal.scaleb(iScale) if precision is not None: vFloat = float(value) if scale: vFloat = pow(vFloat, iScale) except (decimal.InvalidOperation, __HOLE__): # would have been a schema error reported earlier return NaN if precision is not None: if not isinstance(precision, (int,float)): if precision == "INF": precision = floatINF else: try: precision = int(precision) except ValueError: # would be a schema error precision = floatNaN if isinf(precision): vRounded = vDecimal elif precision == 0 or isnan(precision): vRounded = NaN elif vFloat == 0: vRounded = ZERO else: vAbs = fabs(vFloat) log = log10(vAbs) d = precision - int(log) - (1 if vAbs >= 1 else 0) vRounded = decimalRound(vDecimal,d,decimal.ROUND_HALF_UP) elif decimals is not None: if not isinstance(decimals, (int,float)): if decimals == "INF": decimals = floatINF else: try: decimals = int(decimals) except ValueError: # would be a schema error decimals = floatNaN if isinf(decimals): vRounded = vDecimal elif isnan(decimals): vRounded = NaN else: vRounded = decimalRound(vDecimal,decimals,decimal.ROUND_HALF_EVEN) else: vRounded = vDecimal return vRounded
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateXbrlCalcs.py/roundValue
6,071
def insignificantDigits(value, precision=None, decimals=None, scale=None): try: vDecimal = decimal.Decimal(value) if scale: iScale = int(scale) vDecimal = vDecimal.scaleb(iScale) if precision is not None: vFloat = float(value) if scale: vFloat = pow(vFloat, iScale) except (decimal.InvalidOperation, ValueError): # would have been a schema error reported earlier return None if precision is not None: if not isinstance(precision, (int,float)): if precision == "INF": return None else: try: precision = int(precision) except __HOLE__: # would be a schema error return None if isinf(precision) or precision == 0 or isnan(precision) or vFloat == 0: return None else: vAbs = fabs(vFloat) log = log10(vAbs) decimals = precision - int(log) - (1 if vAbs >= 1 else 0) elif decimals is not None: if not isinstance(decimals, (int,float)): if decimals == "INF": return None else: try: decimals = int(decimals) except ValueError: # would be a schema error return None if isinf(decimals) or isnan(decimals): return None else: return None if vDecimal.is_normal() and -28 <= decimals <= 28: # prevent exception with excessive quantization digits if decimals > 0: divisor = ONE.scaleb(-decimals) # fractional scaling doesn't produce scientific notation else: # extra quantize step to prevent scientific notation for decimal number divisor = ONE.scaleb(-decimals).quantize(ONE, decimal.ROUND_HALF_UP) # should never round insignificantDigits = abs(vDecimal) % divisor if insignificantDigits: return (vDecimal // divisor * divisor, # truncated portion of number insignificantDigits) # nsignificant digits portion of number return None
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateXbrlCalcs.py/insignificantDigits
6,072
def list(self): """List Fuel environments.""" try: return self.client.get_all() except __HOLE__: raise RuntimeError(_("Can't list environments. " "Please check server availability."))
SystemExit
dataset/ETHPy150Open openstack/rally/rally/plugins/openstack/scenarios/fuel/utils.py/FuelEnvManager.list
6,073
def create(self, name, release_id=1, network_provider="neutron", deployment_mode="ha_compact", net_segment_type="vlan"): try: env = self.client.create(name, release_id, network_provider, deployment_mode, net_segment_type) except __HOLE__: raise RuntimeError(_("Something went wrong while creating an " "environment. This can happen when " "environment with name %s already exists.") % name) if env: return env raise RuntimeError(_("Environment was not created or was " "created but not returned by server."))
SystemExit
dataset/ETHPy150Open openstack/rally/rally/plugins/openstack/scenarios/fuel/utils.py/FuelEnvManager.create
6,074
def getMipMaps(mesh): mipmaps = {} for effect in mesh.effects: for prop in effect.supported: propval = getattr(effect, prop) if isinstance(propval, collada.material.Map): image_name = propval.sampler.surface.image.path image_data = propval.sampler.surface.image.data try: im = Image.open(StringIO(image_data)) im.load() except __HOLE__: from panda3d.core import Texture from panda3d.core import StringStream from panda3d.core import PNMImage #PIL failed, so lets try DDS reader with panda3d t = Texture(image_name) success = t.readDds(StringStream(image_data)) if success == 0: raise FilterException("Failed to read image file %s" % image_name) #convert DDS to PNG outdata = t.getRamImageAs('RGBA').getData() try: im = Image.fromstring('RGBA', (t.getXSize(), t.getYSize()), outdata) im.load() except IOError: raise FilterException("Failed to read image file %s" % image_name) #Keep JPG in same format since JPG->PNG is pretty bad if im.format == 'JPEG': output_format = 'JPEG' output_extension = 'jpg' output_options = {'quality': 95, 'optimize':True} else: output_format = 'PNG' output_extension = 'png' output_options = {'optimize':True} #store a copy to the original image so we can resize from it directly each time orig_im = im width, height = im.size #round down to power of 2 width = int(math.pow(2, int(math.log(width, 2)))) height = int(math.pow(2, int(math.log(height, 2)))) pil_images = [] while True: im = orig_im.resize((width, height), Image.ANTIALIAS) pil_images.insert(0, im) if width == 1 and height == 1: break width = max(width / 2, 1) height = max(height / 2, 1) tar_buf = StringIO() tar = tarfile.TarFile(fileobj=tar_buf, mode='w') cur_offset = 0 byte_ranges = [] for i, pil_img in enumerate(pil_images): buf = StringIO() pil_img.save(buf, output_format, **output_options) file_len = buf.tell() cur_name = '%dx%d.%s' % (pil_img.size[0], pil_img.size[1], output_extension) tar_info = tarfile.TarInfo(name=cur_name) tar_info.size=file_len buf.seek(0) tar.addfile(tarinfo=tar_info, fileobj=buf) #tar files have a 512 byte header cur_offset += 512 file_start = cur_offset byte_ranges.append({'offset':file_start, 'length':file_len, 'width':pil_img.size[0], 'height':pil_img.size[1]}) #file lengths are rounded up to nearest 512 multiple file_len = 512 * ((file_len + 512 - 1) / 512) cur_offset += file_len tar.close() mipmaps[propval.sampler.surface.image.path] = (tar_buf.getvalue(), byte_ranges) return mipmaps
IOError
dataset/ETHPy150Open pycollada/meshtool/meshtool/filters/optimize_filters/save_mipmaps.py/getMipMaps
6,075
def action(self, destination, data, **kwa): """ Increment corresponding items in destination by items in data if only one field then single increment if multiple fields then vector increment parameters: destination = share to increment sourceData = dict of field values to increment by """ try: dstData = odict() for field in data: dstData[field] = destination[field] + data[field] destination.update(dstData) #update so time stamp updated, use dict except __HOLE__ as ex: #in case value is not a number console.terse("Error in Inc: {0}\n".format(ex)) else: console.profuse("Inc {0} in {1} by {2} to {3}\n".format( data.keys(), destination.name, data.values(), dstData.values()))
TypeError
dataset/ETHPy150Open ioflo/ioflo/ioflo/base/poking.py/IncDirect.action
6,076
def action(self, destination, destinationFields, source, sourceFields, **kwa): """ Increment destinationFields in destination by sourceFields in source parameters: destination = share to increment destinationField = field in share to increment source = share with value to increment by sourceField = field in share with value to increment by """ try: data = odict() for dstField, srcField in izip(destinationFields, sourceFields): data[dstField] = destination[dstField] + source[srcField] destination.update(data) #update so time stamp updated, use dict except __HOLE__ as ex: console.terse("Error in Inc: {0}\n".format(ex1)) else: console.profuse("Inc {0} in {1} from {2} in {3} to {4}\n".format( destinationFields, destination.name, sourceFields, source.name, data.values))
TypeError
dataset/ETHPy150Open ioflo/ioflo/ioflo/base/poking.py/IncIndirect.action
6,077
def _read_one_frame(self): """ Reads a single data frame from the stream and returns it. """ # Keep reading until the stream is closed or we have a data frame. while not self.remote_closed and not self.data: self._recv_cb() try: return self.data.pop(0) except __HOLE__: return None
IndexError
dataset/ETHPy150Open Lukasa/hyper/hyper/http20/stream.py/Stream._read_one_frame
6,078
def Main(): try: import setuptools METADATA.update(SETUPTOOLS_METADATA) setuptools.setup(**METADATA) except __HOLE__: import distutils.core distutils.core.setup(**METADATA)
ImportError
dataset/ETHPy150Open ryanmcgrath/pythentic_jobs/setup.py/Main
6,079
def fail(self): super(RandomExponentialBackoff, self).fail() # Exponential growth with ratio sqrt(2); compute random delay # between x and 2x where x is growing exponentially delay_scale = int(2 ** (self.number_of_retries / 2.0 - 1)) + 1 delay = delay_scale + random.randint(1, delay_scale) message = "Sleeping for %ss [max %s] before retrying." % (delay, delay_scale * 2) try: logger.warning(message) except __HOLE__: print(message) time.sleep(delay)
NameError
dataset/ETHPy150Open zulip/zulip/api/zulip/__init__.py/RandomExponentialBackoff.fail
6,080
def get_user_agent(self): vendor = '' vendor_version = '' try: vendor = platform.system() vendor_version = platform.release() except __HOLE__: # If the calling process is handling SIGCHLD, platform.system() can # fail with an IOError. See http://bugs.python.org/issue9127 pass if vendor == "Linux": vendor, vendor_version, dummy = platform.linux_distribution() elif vendor == "Windows": vendor_version = platform.win32_ver()[1] elif vendor == "Darwin": vendor_version = platform.mac_ver()[0] return "{client_name} ({vendor}; {vendor_version})".format( client_name=self.client_name, vendor=vendor, vendor_version=vendor_version, )
IOError
dataset/ETHPy150Open zulip/zulip/api/zulip/__init__.py/Client.get_user_agent
6,081
def plot_reflection_factor(self, filename=None): """ Plot reflection factor. """ if self.frequency is None: raise ValueError("No frequency specified.") if self.angle is None: raise ValueError("No angle specified.") try: n_f = len(self.frequency) except __HOLE__: n_f = 1 try: n_a = len(self.angle) except TypeError: n_a = 1 if n_f==1 and n_a==1: raise ValueError("Either frequency or angle needs to be a vector.") elif n_f==1 or n_a==1: if n_f==1 and n_a>1:# Show R as function of angle for a single frequency. xlabel = r"$\theta$ in degrees" elif n_f>1 and n_a==1:# Show R as function of frequency for a single angle. xlabel = r"$f$ in Hz" R = self.reflection_factor fig = plt.figure() ax0 = fig.add_subplot(211) ax0.set_title("Magnitude of reflection factor") ax0.semilogx(self.frequency, np.abs(R)) ax0.set_xlabel(xlabel) ax0.set_ylabel(r'$\left|R\right|$') ax0.grid() ax1 = fig.add_subplot(212) ax1.set_title("Phase of reflection factor") ax1.semilogx(self.frequency, np.angle(R)) ax1.set_xlabel(xlabel) ax1.set_ylabel(r'$\angle R$') ax1.grid() elif n_f>1 and n_a>1:# Show 3D or pcolor R = self.reflection_factor fig = plt.figure() #grid = AxesGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.1, cbar_mode='each', cbar_location='right') ax0 = fig.add_subplot(211) #ax0 = grid[0] ax0.set_title("Magnitude of reflection factor") ax0.pcolormesh(self.frequency, self.angle * 180.0 / np.pi, np.abs(R)) #ax0.pcolor(self.angle, self.frequency, np.abs(R)) #ax0.set_xlabel(xlabel) #ax0.set_ylabel(r'$\left|R\right|$') ax0.grid() ax1 = fig.add_subplot(212) #ax1 = grid[1] ax1.set_title("Phase of reflection factor") ax1.pcolormesh(self.frequency, self.angle * 180.0 / np.pi, np.angle(R)) #ax1.pcolor(self.angle, self.frequency, np.angle(R)) #ax0.set_xlabel(xlabel) #ax0.set_ylabel(r'$\angle R$') ax1.grid() else: raise RuntimeError("Oops...") #plt.tight_layout() if filename: fig.savefig(filename, transparant=True) else: return fig
TypeError
dataset/ETHPy150Open python-acoustics/python-acoustics/acoustics/reflection.py/Boundary.plot_reflection_factor
6,082
@dir_app.route('/results/') def get_result_dir_info(): ''' Retrieve results directory information. The backend's results directory is determined by WORK_DIR. All the directories there are formatted and returned as results. If WORK_DIR does not exist, an empty listing will be returned (shown as a 'failure below'). **Successful JSON Response** .. sourcecode:: javascript { 'listing': [ '/bar', '/foo' ] } **Failure JSON Response** .. sourcecode:: javascript { 'listing': [] } ''' dir_info = [] try: dir_listing = os.listdir(WORK_DIR) except __HOLE__: # The WORK_DIR hasn't been created, so we don't have any results! pass else: for obj in dir_listing: # Ignore hidden files if obj[0] == '.': continue # Create a path to the listed object and strip the work dir leader. # If the result isn't a directory, ignore it. obj = os.path.join(WORK_DIR, obj) if not os.path.isdir(obj): continue dir_info.append(obj.replace(WORK_DIR, '')) sorted(dir_info, key=lambda s: s.lower()) if request.query.callback: return "%s(%s)" % (request.query.callback, {'listing': dir_info}) return {'listing': dir_info}
OSError
dataset/ETHPy150Open apache/climate/ocw-ui/backend/directory_helpers.py/get_result_dir_info
6,083
def __init__(self, environment, kwargs): Dependency.__init__(self) self.name = 'boost' self.libdir = '' try: self.boost_root = os.environ['BOOST_ROOT'] if not os.path.isabs(self.boost_root): raise DependencyException('BOOST_ROOT must be an absolute path.') except __HOLE__: self.boost_root = None if self.boost_root is None: if mesonlib.is_windows(): self.boost_root = self.detect_win_root() self.incdir = self.boost_root else: self.incdir = '/usr/include' else: self.incdir = os.path.join(self.boost_root, 'include') self.boost_inc_subdir = os.path.join(self.incdir, 'boost') mlog.debug('Boost library root dir is', self.boost_root) self.src_modules = {} self.lib_modules = {} self.lib_modules_mt = {} self.detect_version() self.requested_modules = self.get_requested(kwargs) module_str = ', '.join(self.requested_modules) if self.version is not None: self.detect_src_modules() self.detect_lib_modules() self.validate_requested() if self.boost_root is not None: info = self.version + ', ' + self.boost_root else: info = self.version mlog.log('Dependency Boost (%s) found:' % module_str, mlog.green('YES'), '(' + info + ')') else: mlog.log("Dependency Boost (%s) found:" % module_str, mlog.red('NO'))
KeyError
dataset/ETHPy150Open mesonbuild/meson/mesonbuild/dependencies.py/BoostDependency.__init__
6,084
def _read_config(self): self.hosts = [] try: if os.path.exists(self.config_path): cfgfile = open(self.config_path, 'r') self.settings = yaml.safe_load(cfgfile.read()) cfgfile.close() # Use the presence of a Description as an indicator this is # a legacy config file: if 'Description' in self.settings: self._upgrade_legacy_config() # Parse the hosts into DTO objects: if 'hosts' in self.settings: for host in self.settings['hosts']: self.hosts.append(Host(**host)) # Watchout for the variant_version coming in as a float: if 'variant_version' in self.settings: self.settings['variant_version'] = \ str(self.settings['variant_version']) except __HOLE__, ferr: raise OOConfigFileError('Cannot open config file "{}": {}'.format(ferr.filename, ferr.strerror)) except yaml.scanner.ScannerError: raise OOConfigFileError( 'Config file "{}" is not a valid YAML document'.format(self.config_path))
IOError
dataset/ETHPy150Open openshift/openshift-ansible/utils/src/ooinstall/oo_config.py/OOConfig._read_config
6,085
@classmethod def _validate_structure(cls, structure, name, authorized_types): """ validate if all fields in self.structure are in authorized types. """ ############## def __validate_structure(struct, name, _authorized): if type(struct) is type: if struct not in authorized_types: if struct not in authorized_types: raise StructureError("%s: %s is not an authorized type" % (name, struct)) elif isinstance(struct, dict): for key in struct: if isinstance(key, basestring): if "." in key: raise BadKeyError("%s: %s must not contain '.'" % (name, key)) if key.startswith('$'): raise BadKeyError("%s: %s must not start with '$'" % (name, key)) elif type(key) is type: if not key in authorized_types: raise AuthorizedTypeError("%s: %s is not an authorized type" % (name, key)) else: raise StructureError("%s: %s must be a basestring or a type" % (name, key)) if struct[key] is None: pass elif isinstance(struct[key], dict): __validate_structure(struct[key], name, authorized_types) elif isinstance(struct[key], list): __validate_structure(struct[key], name, authorized_types) elif isinstance(struct[key], tuple): __validate_structure(struct[key], name, authorized_types) elif isinstance(struct[key], CustomType): __validate_structure(struct[key].mongo_type, name, authorized_types) elif isinstance(struct[key], SchemaProperties): pass elif isinstance(struct[key], SchemaOperator): __validate_structure(struct[key], name, authorized_types) elif hasattr(struct[key], 'structure'): __validate_structure(struct[key], name, authorized_types) elif struct[key] not in authorized_types: ok = False for auth_type in authorized_types: if struct[key] is None: ok = True else: try: if isinstance(struct[key], auth_type) or issubclass(struct[key], auth_type): ok = True except __HOLE__: raise TypeError("%s: %s is not a type" % (name, struct[key])) if not ok: raise StructureError( "%s: %s is not an authorized type" % (name, struct[key])) elif isinstance(struct, list) or isinstance(struct, tuple): for item in struct: __validate_structure(item, name, authorized_types) elif isinstance(struct, SchemaOperator): if isinstance(struct, IS): for operand in struct: if type(operand) not in authorized_types: raise StructureError("%s: %s in %s is not an authorized type (%s found)" % ( name, operand, struct, type(operand).__name__)) else: for operand in struct: if operand not in authorized_types: raise StructureError("%s: %s in %s is not an authorized type (%s found)" % ( name, operand, struct, type(operand).__name__)) elif isinstance(struct, SchemaProperties): pass else: ok = False for auth_type in authorized_types: if isinstance(struct, auth_type): ok = True if not ok: raise StructureError("%s: %s is not an authorized_types" % (name, struct)) ################# if structure is None: raise StructureError("%s.structure must not be None" % name) if not isinstance(structure, dict): raise StructureError("%s.structure must be a dict instance" % name) __validate_structure(structure, name, authorized_types)
TypeError
dataset/ETHPy150Open namlook/mongokit/mongokit/schema_document.py/SchemaDocument._validate_structure
6,086
def HashFile(theFile,simplename,o_result): if os.path.exists(theFile): if os.path.isfile(theFile): try: f=open(theFile,'rb') except __HOLE__: log.warning("open failed :"+theFile) return else: try: rd = f.read() except IOError: f.close() log.warning("read failed:"+theFile) return else: theFileStats=os.stat(theFile) (mode,ino,dev,nlink,uid,gid,size,atime,mtime,ctime)=os.stat(theFile) log.info("Processing File: "+theFile) fileSize = str(size) modifiedTIme= time.ctime(mtime) accessTime = time.ctime(atime) createdTime = time.ctime(ctime) ownerID = str(uid) groupID = str(gid) fileMode = bin(mode) if gl_args.md5: hashout = hashlib.md5() hashout.update(rd) hexmd5 = hashout.hexdigest() hashValue = hexmd5.upper() elif gl_args.sha256: hashout = hashlib.sha256() hashout.update(rd) hexsha256 = hashout.hexdigest() hashValue = hexsha256.upper() elif gl_args.sha512: hashout = hashlib.sha512() hashout.update(rd) hexsha512 = hashout.hexdigest() hashValue = hexsha512.upper() else: log.error("hash not Selected") f.close() o_result.writeCSVrow(simplename,theFile,fileSize,modifiedTIme,accessTime,createdTime,hashValue,ownerID,groupID,mode) return True else: log.warning("cannot read the file :"+theFile) return False else: log.warning("not a file"+theFile) return False
IOError
dataset/ETHPy150Open girishramnani/hacking-tools/file_hasher/_pfish_tools.py/HashFile
6,087
def test_invalid_input_line(self): caught_exception = False try: position = DocumentMapping.Position("app.js", -1, 0) except __HOLE__: caught_exception = True self.assertTrue(caught_exception)
ValueError
dataset/ETHPy150Open sokolovstas/SublimeWebInspector/tests/DocumentMappingTests.py/PositionTests.test_invalid_input_line
6,088
def test_invalid_input_column(self): caught_exception = False try: position = DocumentMapping.Position("app.js", 0, -1) except __HOLE__: caught_exception = True self.assertTrue(caught_exception)
ValueError
dataset/ETHPy150Open sokolovstas/SublimeWebInspector/tests/DocumentMappingTests.py/PositionTests.test_invalid_input_column
6,089
def test_invalid_input(self): caught_exception = False try: position = DocumentMapping.Position("app.js", -4, -3) except __HOLE__: caught_exception = True self.assertTrue(caught_exception)
ValueError
dataset/ETHPy150Open sokolovstas/SublimeWebInspector/tests/DocumentMappingTests.py/PositionTests.test_invalid_input
6,090
def reply2har(reply, include_content=False, binary_content=False): """ Serialize QNetworkReply to HAR. """ res = { "httpVersion": "HTTP/1.1", # XXX: how to get HTTP version? "cookies": reply_cookies2har(reply), "headers": headers2har(reply), "content": { "size": 0, "mimeType": "", }, "headersSize": headers_size(reply), # non-standard but useful "ok": not reply.error(), # non-standard, useful because reply url may not equal request url # in case of redirect "url": reply.url().toString() } content_type = reply.header(QNetworkRequest.ContentTypeHeader) if content_type is not None: res["content"]["mimeType"] = six.text_type(content_type) content_length = reply.header(QNetworkRequest.ContentLengthHeader) if content_length is not None: # this is not a correct way to get the size! res["content"]["size"] = content_length status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) if status is not None: res["status"] = int(status) else: res["status"] = 0 status_text = reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute) if status_text is not None: try: res["statusText"] = bytes(status_text, 'latin1').decode('latin1') except __HOLE__: res["statusText"] = bytes(status_text).decode('latin1') else: res["statusText"] = REQUEST_ERRORS_SHORT.get(reply.error(), "?") redirect_url = reply.attribute(QNetworkRequest.RedirectionTargetAttribute) if redirect_url is not None: res["redirectURL"] = six.text_type(redirect_url.toString()) else: res["redirectURL"] = "" if include_content: data = bytes(reply.readAll()) if binary_content: res["content"]["encoding"] = "binary" res["content"]["text"] = data res["content"]["size"] = len(data) else: res["content"]["encoding"] = "base64" res["content"]["text"] = base64.b64encode(data) res["content"]["size"] = len(data) return res
TypeError
dataset/ETHPy150Open scrapinghub/splash/splash/har/qt.py/reply2har
6,091
def on_post(self, req, resp, tenant_id): body = json.loads(req.stream.read().decode()) try: name = body['keypair']['name'] key = body['keypair'].get('public_key', generate_random_key()) except (__HOLE__, TypeError): return error_handling.bad_request( resp, 'Not all fields exist to create keypair.') validate_result = validate_keypair_name(resp, name) if not validate_result: return client = req.env['sl_client'] mgr = SoftLayer.SshKeyManager(client) # Make sure the key with that label doesn't already exist existing_keys = mgr.list_keys(label=name) if existing_keys: return error_handling.duplicate(resp, 'Duplicate key by that name') try: keypair = mgr.add_key(key, name) resp.body = {'keypair': format_keypair(keypair)} except SoftLayer.SoftLayerAPIError as e: if 'Unable to generate a fingerprint' in e.faultString: return error_handling.bad_request(resp, e.faultString) if 'SSH key already exists' in e.faultString: return error_handling.duplicate(resp, e.faultString) raise
KeyError
dataset/ETHPy150Open softlayer/jumpgate/jumpgate/compute/drivers/sl/keypairs.py/KeypairsV2.on_post
6,092
@destructiveTest @skipIf(os.getuid() != 0, 'You must be logged in as root to run this test') @requires_system_grains def test_mac_group_chgid(self, grains=None): ''' Tests changing the group id ''' # Create a group to delete - If unsuccessful, skip the test if self.run_function('group.add', [CHANGE_GROUP, 5678]) is not True: self.run_function('group.delete', [CHANGE_GROUP]) self.skipTest('Failed to create a group to manipulate') try: self.run_function('group.chgid', [CHANGE_GROUP, 6789]) group_info = self.run_function('group.info', [CHANGE_GROUP]) self.assertEqual(group_info['gid'], 6789) except __HOLE__: self.run_function('group.delete', [CHANGE_GROUP]) raise
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/modules/mac_group.py/MacGroupModuleTest.test_mac_group_chgid
6,093
@destructiveTest @skipIf(os.getuid() != 0, 'You must be logged in as root to run this test') @requires_system_grains def test_mac_adduser(self, grains=None): ''' Tests adding user to the group ''' # Create a group to use for test - If unsuccessful, skip the test if self.run_function('group.add', [ADD_GROUP, 5678]) is not True: self.run_function('group.delete', [ADD_GROUP]) self.skipTest('Failed to create a group to manipulate') try: self.run_function('group.adduser', [ADD_GROUP, ADD_USER]) group_info = self.run_function('group.info', [ADD_GROUP]) self.assertEqual(ADD_USER, ''.join(group_info['members'])) except __HOLE__: self.run_function('group.delete', [ADD_GROUP]) raise
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/modules/mac_group.py/MacGroupModuleTest.test_mac_adduser
6,094
def __init__(self, message): try: self.picurl = message.pop('PicUrl') self.media_id = message.pop('MediaId') except __HOLE__: raise ParseError() super(ImageMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/ImageMessage.__init__
6,095
def __init__(self, message): try: self.media_id = message.pop('MediaId') self.thumb_media_id = message.pop('ThumbMediaId') except __HOLE__: raise ParseError() super(VideoMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/VideoMessage.__init__
6,096
def __init__(self, message): try: self.media_id = message.pop('MediaId') self.thumb_media_id = message.pop('ThumbMediaId') except __HOLE__: raise ParseError() super(ShortVideoMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/ShortVideoMessage.__init__
6,097
def __init__(self, message): try: location_x = message.pop('Location_X') location_y = message.pop('Location_Y') self.location = (float(location_x), float(location_y)) self.scale = int(message.pop('Scale')) self.label = message.pop('Label') except __HOLE__: raise ParseError() super(LocationMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/LocationMessage.__init__
6,098
def __init__(self, message): try: self.title = message.pop('Title') self.description = message.pop('Description') self.url = message.pop('Url') except __HOLE__: raise ParseError() super(LinkMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/LinkMessage.__init__
6,099
def __init__(self, message): message.pop('type') try: self.type = message.pop('Event').lower() if self.type == 'subscribe' or self.type == 'scan': self.key = message.pop('EventKey', None) self.ticket = message.pop('Ticket', None) elif self.type in ['click', 'scancode_push', 'scancode_waitmsg', 'pic_sysphoto', 'pic_photo_or_album', 'pic_weixin', 'location_select']: self.key = message.pop('EventKey', None) elif self.type == 'view': self.key = message.pop('EventKey', None) self.menu_id = message.pop('MenuId', None) elif self.type == 'location': self.latitude = float(message.pop('Latitude', '0')) self.longitude = float(message.pop('Longitude', '0')) self.precision = float(message.pop('Precision', '0')) elif self.type == 'templatesendjobfinish': self.status = message.pop('Status', None) except __HOLE__: raise ParseError() super(EventMessage, self).__init__(message)
KeyError
dataset/ETHPy150Open wechat-python-sdk/wechat-python-sdk/wechat_sdk/messages.py/EventMessage.__init__