auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void safeRun() { boolean force = forceGarbageCollection.get(); if (force) { LOG.info("Garbage collector thread forced to perform GC before expiry of wait time."); } if (compactor instanceof TransactionalEntryLogCompactor) { ((TransactionalEntryLogCompactor) compactor).cleanUpAndRecover(); } entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); doGcLedgers(); doGcEntryLogs(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); if (suspendMajor) { LOG.info("Disk almost full, suspend major compaction to slow down filling disk."); } if (suspendMinor) { LOG.info("Disk full, suspend minor compaction to slow down filling disk."); } long curTime = MathUtils.now(); if (enableMajorCompaction && (!suspendMajor) && (force || curTime - lastMajorCompactionTime > majorCompactionInterval)) { LOG.info("Enter major compaction, suspendMajor {}", suspendMajor); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = MathUtils.now(); lastMinorCompactionTime = lastMajorCompactionTime; forceGarbageCollection.set(false); return; } if (enableMinorCompaction && (!suspendMinor) && (force || curTime - lastMinorCompactionTime > minorCompactionInterval)) { LOG.info("Enter minor compaction, suspendMinor {}", suspendMinor); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = MathUtils.now(); } forceGarbageCollection.set(false); }

Target:
public void safeRun() { boolean force = forceGarbageCollection.get(); if (force) { LOG.info("Garbage collector thread forced to perform GC before expiry of wait time."); } compactor.cleanUpAndRecover(); entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); doGcLedgers(); doGcEntryLogs(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); if (suspendMajor) { LOG.info("Disk almost full, suspend major compaction to slow down filling disk."); } if (suspendMinor) { LOG.info("Disk full, suspend minor compaction to slow down filling disk."); } long curTime = MathUtils.now(); if (enableMajorCompaction && (!suspendMajor) && (force || curTime - lastMajorCompactionTime > majorCompactionInterval)) { LOG.info("Enter major compaction, suspendMajor {}", suspendMajor); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = MathUtils.now(); lastMinorCompactionTime = lastMajorCompactionTime; forceGarbageCollection.set(false); return; } if (enableMinorCompaction && (!suspendMinor) && (force || curTime - lastMinorCompactionTime > minorCompactionInterval)) { LOG.info("Enter minor compaction, suspendMinor {}", suspendMinor); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = MathUtils.now(); } forceGarbageCollection.set(false); }
Source:
private void onDeleteClicked(Spinner spinner) { String reason = spinner.getSelectedItem().toString(); Single<String> deletionReason = reasonBuilder.getReason(media, reason); deletionReason .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s -> { if(null!=getActivity()) { deleteTask = new DeleteTask(getActivity(), media, reason); deleteTask.execute(); } isDeleted = true; enableDeleteButton(false); }); }

Target:
private void onDeleteClicked(Spinner spinner) { String reason = spinner.getSelectedItem().toString(); Single<String> deletionReason = reasonBuilder.getReason(media, reason); deletionReason .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s -> { if (getActivity() != null) { deleteTask = new DeleteTask(getActivity(), media, reason); deleteTask.execute(); isDeleted = true; enableDeleteButton(false); } }); }
Source:
public FieldInfo relationshipField(String relationshipName, Direction relationshipDirection, boolean strict) { for (FieldInfo fieldInfo : relationshipFields()) { String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship(); if (relationshipName.equalsIgnoreCase(relationship)) { if (((fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.INCOMING) || fieldInfo .relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.UNDIRECTED)) && (relationshipDirection.equals(Direction.INCOMING))) || (relationshipDirection.equals(Direction.OUTGOING) && !(fieldInfo .relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.INCOMING)))) { return fieldInfo; } } } return null; }

Target:
public FieldInfo relationshipField(String relationshipName, Direction relationshipDirection, boolean strict) { for (FieldInfo fieldInfo : relationshipFields()) { String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship(); if (relationshipName.equalsIgnoreCase(relationship)) { Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING); if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) { return fieldInfo; } } } return null; }
Source:
public String getCellDataValueByPosition(int row, int col) { assertIsLegalCell(row, col); Object obj = widget.getDataValueByPosition(col, row); if(obj != null) { return obj.toString(); } else return ""; }

Target:
public String getCellDataValueByPosition(int row, int col) { assertIsLegalCell(row, col); Object obj = widget.getDataValueByPosition(col, row); if (obj != null) { return obj.toString(); } else { return ""; } }
Source:
public Predicate<ChangeData> message(String text) { return new MessagePredicate(args.dbProvider, args.repoManager, args.index, text); }

Target:
public Predicate<ChangeData> message(String text) { return new MessagePredicate(args.dbProvider, args.index, text); }
Source:
private List<KeyValue<Windowed<String>, Long>> toList(final KeyValueIterator<Bytes, byte[]> iterator) { final List<KeyValue<Windowed<String>, Long>> results = new ArrayList<>(); final StateSerdes<String, Long> stateSerdes = StateSerdes.withBuiltinTypes("dummy", String.class, Long.class); while (iterator.hasNext()) { final KeyValue<Bytes, byte[]> next = iterator.next(); final KeyValue<Windowed<String>, Long> deserialized; if (schema instanceof WindowKeySchema) { deserialized = KeyValue.pair( WindowKeySchema.fromStoreKey( next.key.get(), windowSizeForTimeWindow, stateSerdes.keyDeserializer(), stateSerdes.topic() ), stateSerdes.valueDeserializer().deserialize("dummy", next.value) ); } else { deserialized = KeyValue.pair( SessionKeySchema.from(next.key.get(), stateSerdes.keyDeserializer(), "dummy"), stateSerdes.valueDeserializer().deserialize("dummy", next.value) ); } results.add(deserialized); } return results; }

Target:
private List<KeyValue<Windowed<String>, Long>> toList(final KeyValueIterator<Bytes, byte[]> iterator) { final List<KeyValue<Windowed<String>, Long>> results = new ArrayList<>(); final StateSerdes<String, Long> stateSerdes = StateSerdes.withBuiltinTypes("dummy", String.class, Long.class); while (iterator.hasNext()) { final KeyValue<Bytes, byte[]> next = iterator.next(); if (schema instanceof WindowKeySchema) { final KeyValue<Windowed<String>, Long> deserialized = KeyValue.pair( WindowKeySchema.fromStoreKey( next.key.get(), windowSizeForTimeWindow, stateSerdes.keyDeserializer(), stateSerdes.topic() ), stateSerdes.valueDeserializer().deserialize("dummy", next.value) ); results.add(deserialized); } else { final KeyValue<Windowed<String>, Long> deserialized = KeyValue.pair( SessionKeySchema.from(next.key.get(), stateSerdes.keyDeserializer(), "dummy"), stateSerdes.valueDeserializer().deserialize("dummy", next.value) ); results.add(deserialized); } } return results; }
Source:
public Response getMainPage() throws URISyntaxException, IOException, FreeMarkerException { if (!uriInfo.getRequestUri().getPath().endsWith("/")) { return Response.status(302).location(uriInfo.getRequestUriBuilder().path("/").build()).build(); } else { Map<String, Object> map = new HashMap<>(); URI baseUri = uriInfo.getBaseUri(); map.put("authUrl", session.getContext().getContextPath()); map.put("baseUrl", session.getContext().getContextPath() + "/realms/" + realm.getName() + "/account"); map.put("realm", realm.getName()); map.put("resourceUrl", Urls.themeRoot(baseUri).getPath() + "/account/" + theme.getName()); map.put("resourceVersion", Version.RESOURCES_VERSION); String[] referrer = getReferrer(); if (referrer != null) { map.put("referrer", referrer[0]); map.put("referrer_uri", referrer[1]); } try { if (auth != null) { Locale locale = session.getContext().resolveLocale(auth.getUser()); map.put("locale", locale.toLanguageTag()); Properties messages = theme.getMessages(locale); map.put("javaMessages", new MessageFormatterMethod(locale, messages)); map.put("msg", messagesToJsonString(messages)); } } catch (Exception e) { logger.warn("Failed to load messages", e); } map.put("properties", theme.getProperties()); FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil(); String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); BrowserSecurityHeaderSetup.headers(builder, realm); return builder.build(); } }

Target:
public Response getMainPage() throws URISyntaxException, IOException, FreeMarkerException { if (!uriInfo.getRequestUri().getPath().endsWith("/")) { return Response.status(302).location(uriInfo.getRequestUriBuilder().path("/").build()).build(); } else { Map<String, Object> map = new HashMap<>(); URI baseUri = uriInfo.getBaseUri(); map.put("authUrl", session.getContext().getContextPath()); map.put("baseUrl", session.getContext().getContextPath() + "/realms/" + realm.getName() + "/account"); map.put("realm", realm.getName()); map.put("resourceUrl", Urls.themeRoot(baseUri).getPath() + "/account/" + theme.getName()); map.put("resourceVersion", Version.RESOURCES_VERSION); String[] referrer = getReferrer(); if (referrer != null) { map.put("referrer", referrer[0]); map.put("referrer_uri", referrer[1]); } try { if (auth != null) { Locale locale = session.getContext().resolveLocale(auth.getUser()); map.put("locale", locale.toLanguageTag()); Properties messages = theme.getMessages(locale); map.put("msg", messagesToJsonString(messages)); } } catch (Exception e) { logger.warn("Failed to load messages", e); } map.put("properties", theme.getProperties()); FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil(); String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); BrowserSecurityHeaderSetup.headers(builder, realm); return builder.build(); } }
Source:
protected void validate(CompilationUnit unit, ProblemCollector collector) { if (Utils.isSequenceDiagramDescription(unit)) { unit.accept(new SequenceDiagramVisitor(collector)); } }

Target:
protected void validate(CompilationUnit unit, ProblemCollector collector) { if (!ElementTypeTeller.isModelElement(unit)) { unit.accept(new SequenceDiagramVisitor(collector)); } }
Source:
public boolean attachManagedBlockStorageDisks(VM vm, VmHandler vmHandler, VDS vds) { if (vm.getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(vm); } List<ManagedBlockStorageDisk> disks = DisksFilter.filterManagedBlockStorageDisks(vm.getDiskMap().values()); if (vds.getConnectorInfo() == null && !disks.isEmpty()) { AuditLogable event = new AuditLogableImpl(); event.addCustomValue("VdsName", vds.getName()); event.addCustomValue("VmName", vm.getName()); auditLogDirector.log(event, AuditLogType.CONNECTOR_INFO_MISSING_ON_VDS); return false; } return disks.stream() .allMatch(disk -> { VmDevice vmDevice = vmDeviceDao.get(new VmDeviceId(disk.getImageId(), vm.getId())); return this.saveDevices(disk, vds, vmDevice); }); }

Target:
public boolean attachManagedBlockStorageDisks(VM vm, VmHandler vmHandler, VDS vds) { if (vm.getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(vm); } List<ManagedBlockStorageDisk> disks = DisksFilter.filterManagedBlockStorageDisks(vm.getDiskMap().values()); if (!disks.isEmpty() && vds.getConnectorInfo() == null) { AuditLogable event = new AuditLogableImpl(); event.addCustomValue("VdsName", vds.getName()); event.addCustomValue("VmName", vm.getName()); auditLogDirector.log(event, AuditLogType.CONNECTOR_INFO_MISSING_ON_VDS); return false; } return disks.stream() .allMatch(disk -> { VmDevice vmDevice = vmDeviceDao.get(new VmDeviceId(disk.getImageId(), vm.getId())); return this.saveDevices(disk, vds, vmDevice); }); }
Source:
public static boolean isKeyFrame(byte[] buff, int off, int len) { if (buff == null || buff.length < off + len || len < RTPHeader.SIZE) { return false; } if (!DePacketizer.VP8PayloadDescriptor.isValid(buff, off)) { return false; } if (!DePacketizer.VP8PayloadDescriptor.isStartOfFrame(buff, off)) { return false; } int szVP8PayloadDescriptor = DePacketizer .VP8PayloadDescriptor.getSize(buff, off); return DePacketizer.VP8PayloadHeader.isKeyFrame( buff, off + szVP8PayloadDescriptor); }

Target:
public static boolean isKeyFrame(byte[] buff, int off, int len) { if (buff == null || buff.length < off + len || len < RawPacket.FIXED_HEADER_SIZE) { return false; } if (!DePacketizer.VP8PayloadDescriptor.isValid(buff, off)) { return false; } if (!DePacketizer.VP8PayloadDescriptor.isStartOfFrame(buff, off)) { return false; } int szVP8PayloadDescriptor = DePacketizer .VP8PayloadDescriptor.getSize(buff, off); return DePacketizer.VP8PayloadHeader.isKeyFrame( buff, off + szVP8PayloadDescriptor); }
Source:
protected ViewModel doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String sptoken = Strings.clean(fieldValueResolver.getValue(request, "sptoken")); if (sptoken == null) { if (isJsonPreferred(request, response)) { Map<String,Object> model = new HashMap<String, Object>(); model.put("status", HttpServletResponse.SC_BAD_REQUEST); model.put("message", i18n(request, "stormpath.web.verifyEmail.form.errors.noToken")); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return new DefaultViewModel("stormpathJsonView", model); } Map<String, ?> model = createModel(request, response); return new DefaultViewModel(view, model).setRedirect(false); } try { return verify(request, response, sptoken); } catch (Exception e) { if (isJsonPreferred(request, response)) { Map<String,Object> model = errorModelFactory.toError(request, e).toMap(); errorModelFactory.toError(request, e); response.setStatus(errorModelFactory.toError(request, e).getStatus()); return new DefaultViewModel("stormpathJsonView", model); } List<ErrorModel> errors = new ArrayList<ErrorModel>(); ErrorModel error = ErrorModel.builder().setStatus(HttpServletResponse.SC_BAD_REQUEST).setMessage(i18n(request, "stormpath.web.verifyEmail.form.errors.invalidLink")).build(); errors.add(error); Map<String, ?> model = createModel(request, response, null, errors); return new DefaultViewModel(view, model); } }

Target:
protected ViewModel doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String sptoken = Strings.clean(request.getParameter("sptoken")); if (sptoken == null) { if (isJsonPreferred(request, response)) { Map<String,Object> model = new HashMap<String, Object>(); model.put("status", HttpServletResponse.SC_BAD_REQUEST); model.put("message", i18n(request, "stormpath.web.verifyEmail.form.errors.noToken")); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return new DefaultViewModel(STORMPATH_JSON_VIEW_NAME, model); } Map<String, ?> model = createModel(request, response); return new DefaultViewModel(view, model).setRedirect(false); } try { return verify(request, response, sptoken); } catch (Exception e) { if (isJsonPreferred(request, response)) { ErrorModel error = errorModelFactory.toError(request, e); response.setStatus(error.getStatus()); Map<String,Object> model = error.toMap(); return new DefaultViewModel(STORMPATH_JSON_VIEW_NAME, model); } List<ErrorModel> errors = new ArrayList<ErrorModel>(); ErrorModel error = ErrorModel.builder().setStatus(HttpServletResponse.SC_BAD_REQUEST).setMessage(i18n(request, "stormpath.web.verifyEmail.form.errors.invalidLink")).build(); errors.add(error); Map<String, ?> model = createModel(request, response, null, errors); return new DefaultViewModel(view, model); } }
Source:
public void testCountMismatches(final String readString, final String cigar, final String reference, final int expectedMismatchesExact, final int expectedMismatchesAmbiguous) { final SAMRecord rec = new SAMRecord(null); rec.setReadName("test"); rec.setReadString(readString); final byte[] byteArray = new byte[readString.length()]; for(int i =0; i< readString.length();i++){ byteArray[i]=(byte)33; } rec.setBaseQualities(byteArray); rec.setCigarString(cigar); final byte[] refBases = StringUtil.stringToBytes(reference); final int nExact = SequenceUtil.countMismatches(rec, refBases, -1, false, false); Assert.assertEquals(nExact, expectedMismatchesExact); final int sumMismatchesQualityExact = SequenceUtil.sumQualitiesOfMismatches(rec, refBases, -1, false); Assert.assertEquals(sumMismatchesQualityExact, expectedMismatchesExact * 33); final int nAmbiguous = SequenceUtil.countMismatches(rec, refBases, -1, false, true); Assert.assertEquals(nAmbiguous, expectedMismatchesAmbiguous); }

Target:
public void testCountMismatches(final String readString, final String cigar, final String reference, final int expectedMismatchesExact, final int expectedMismatchesAmbiguous) { final SAMRecord rec = new SAMRecord(null); rec.setReadName("test"); rec.setReadString(readString); final byte[] byteArray = new byte[readString.length()]; Arrays.fill(byteArray, (byte)33); rec.setBaseQualities(byteArray); rec.setCigarString(cigar); final byte[] refBases = StringUtil.stringToBytes(reference); final int nExact = SequenceUtil.countMismatches(rec, refBases, -1, false, false); Assert.assertEquals(nExact, expectedMismatchesExact); final int sumMismatchesQualityExact = SequenceUtil.sumQualitiesOfMismatches(rec, refBases, -1, false); Assert.assertEquals(sumMismatchesQualityExact, expectedMismatchesExact * 33); final int nAmbiguous = SequenceUtil.countMismatches(rec, refBases, -1, false, true); Assert.assertEquals(nAmbiguous, expectedMismatchesAmbiguous); }
Source:
public GavinJobExecution findGavinJobExecution(String jobIdentifier) { GavinJobExecution result = dataService.findOneById(GAVIN_JOB_EXECUTION, jobIdentifier, GavinJobExecution.class); if (result == null) { throw new UnknownEntityException(dataService.getEntityType(GAVIN_JOB_EXECUTION), jobIdentifier); } return result; }

Target:
public GavinJobExecution findGavinJobExecution(String jobIdentifier) { GavinJobExecution result = dataService.findOneById(GAVIN_JOB_EXECUTION, jobIdentifier, GavinJobExecution.class); if (result == null) { throw new UnknownEntityException(gavinJobExecutionMetaData, jobIdentifier); } return result; }
Source:
public void visitToken(DetailAST ast) { DetailAST astNode; switch (ast.getType()) { case TokenTypes.TYPECAST: astNode = ast.findFirstToken(TokenTypes.RPAREN); break; case TokenTypes.ARRAY_DECLARATOR: astNode = getArrayDeclaratorPreviousElement(ast); break; case TokenTypes.INDEX_OP: astNode = getIndexOpPreviousElement(ast); break; default: astNode = ast; } final String line = getLine(ast.getLineNo() - 1); final int after = getPositionAfter(astNode); if ((after >= line.length() || Character.isWhitespace(line.charAt(after))) && hasRedundantWhitespace(line, after)) { log(astNode.getLineNo(), after, MSG_KEY, astNode.getText()); } }

Target:
public void visitToken(DetailAST ast) { final DetailAST whitespaceFollowedAst = getWhitespaceFollowedNode(ast); final int whitespaceColumnNo = getPositionAfter(whitespaceFollowedAst); final int whitespaceLineNo = whitespaceFollowedAst.getLineNo(); if (hasTrailingWhitespace(ast, whitespaceColumnNo, whitespaceLineNo)) { log(whitespaceLineNo, whitespaceColumnNo, MSG_KEY, whitespaceFollowedAst.getText()); } }
Source:
private List<Observation> convertObservationMapToList(Map<String, String> observations, DateTime obsDatetime) { List<Observation> observationList = new ArrayList<>(); for (String observationConceptName : observations.keySet()) { if (valueIsNotEmpty(observations, observationConceptName)) { String[] observationValues = observations.get(observationConceptName).replace(", ", ",").split(","); for (String value : observationValues) { if (value != null && !value.isEmpty()) { Observation observation = new Observation(); ConceptName conceptName = new ConceptName(observationConceptName); Concept concept = new Concept(conceptName); observation.setConcept(concept); Observation.ObservationValue observationValue = new Observation.ObservationValue(value); observation.setValue(observationValue); observation.setObsDatetime(obsDatetime.toDate()); observationList.add(observation); } } } else { LOGGER.warn("Observation value is null or empty for concept: " + observationConceptName + " and will not be created"); } } return observationList; }

Target:
private List<Observation> convertObservationMapToList(Map<String, String> observations, DateTime obsDatetime) { List<Observation> observationList = new ArrayList<>(); for (String observationConceptName : observations.keySet()) { if (valueIsNotEmpty(observations, observationConceptName)) { String[] observationValues = observations.get(observationConceptName).replace(", ", ",").split(","); for (String value : observationValues) { if (StringUtils.isNotEmpty(value)) { Observation observation = new Observation(); ConceptName conceptName = new ConceptName(observationConceptName); Concept concept = new Concept(conceptName); observation.setConcept(concept); Observation.ObservationValue observationValue = new Observation.ObservationValue(value); observation.setValue(observationValue); observation.setObsDatetime(obsDatetime.toDate()); observationList.add(observation); } } } else { LOGGER.warn("Observation value is null or empty for concept: " + observationConceptName + " and will not be created"); } } return observationList; }
Source:
public static String autoConvert(long size , SizeUnit inUnit) { for(long i = (SizeUnit.values())[SizeUnit.values().length - 1].getUnitWeight(); i >= inUnit.getUnitWeight(); i-- ) { if(size/Math.pow(CONVERT_FACTOR, i-1) >= 1) { return ((String.valueOf(convert(size, inUnit, SizeUnit.getUnit(i)).floatValue())).concat(" ")).concat(SizeUnit.getUnit(i).toString()); } } return String.valueOf(size).concat(" ").concat(SizeUnit.BYTES.toString()); }

Target:
public static Size autoConvert(long size , SizeUnit inUnit) { for(long i = (SizeUnit.values())[SizeUnit.values().length - 1].getUnitWeight(); i >= inUnit.getUnitWeight(); i-- ) { if(size/Math.pow(CONVERT_FACTOR, i-1) >= 1) { return new SizeConverter.Size(SizeConverter.SizeUnit.getUnit(i), SizeConverter.convert(size, inUnit, SizeUnit.getUnit(i)).doubleValue()); } } return new Size(SizeUnit.BYTES, new Double(new Long(size))); }
Source:
public void testAddNetworkToNicAlongWithAddingItIntoBond() { Network networkA = createNetworkWithName("networkA"); VdsNetworkInterface nicA = createNic("nicA"); VdsNetworkInterface nicB = createNic("nicB"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA, (Guid)null); networkAttachment.setNicId(nicA.getId()); networkAttachment.setNicName(nicA.getName()); networkAttachment.setNetworkId(networkA.getId()); networkAttachment.setNetworkName(networkA.getName()); Bond bond = new Bond(); bond.setName("bond1"); setBondSlaves(bond, nicA, nicB); addNetworkIdToNetworkDaoMock(networkA); addNetworkToClusterDaoMock(networkA.getId()); HostSetupNetworksValidator validator = new HostSetupNetworksValidatorBuilder() .setParams(new ParametersBuilder() .addNetworkAttachments(networkAttachment) .addBonds(CreateOrUpdateBond.fromBond(bond)) .build()) .addExistingInterfaces(nicA, nicB) .addNetworks(networkA) .build(); ValidationResult validate = validator.validate(); assertThat(validate, not(isValid())); EngineMessage engineMessage = EngineMessage.NETWORK_INTERFACE_ADDED_TO_BOND_AND_NETWORK_IS_ATTACHED_TO_IT_AT_THE_SAME_TIME; assertThat(validate, failsWith(engineMessage, ReplacementUtils.getVariableAssignmentString(engineMessage, nicA.getName()), ReplacementUtils.createSetVariableString(HostSetupNetworksValidator.VAR_NETWORK_NAME, networkA.getName()))); }

Target:
public void testAddNetworkToNicAlongWithAddingItIntoBond() { Network networkA = createNetworkWithName("networkA"); VdsNetworkInterface nicA = createNic("nicA"); VdsNetworkInterface nicB = createNic("nicB"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA, (Guid)null); networkAttachment.setNicId(nicA.getId()); networkAttachment.setNicName(nicA.getName()); networkAttachment.setNetworkId(networkA.getId()); networkAttachment.setNetworkName(networkA.getName()); CreateOrUpdateBond createOrUpdateBond = createNewCreateOrUpdateBond(Guid.newGuid(), "bond1", nicA.getName(), nicB.getName()); addNetworkIdToNetworkDaoMock(networkA); addNetworkToClusterDaoMock(networkA.getId()); HostSetupNetworksValidator validator = new HostSetupNetworksValidatorBuilder() .setParams(new ParametersBuilder() .addNetworkAttachments(networkAttachment) .addBonds(createOrUpdateBond) .build()) .addExistingInterfaces(nicA, nicB) .addNetworks(networkA) .build(); ValidationResult validate = validator.validate(); assertThat(validate, not(isValid())); EngineMessage engineMessage = EngineMessage.NETWORK_INTERFACE_ADDED_TO_BOND_AND_NETWORK_IS_ATTACHED_TO_IT_AT_THE_SAME_TIME; assertThat(validate, failsWith(engineMessage, ReplacementUtils.getVariableAssignmentString(engineMessage, nicA.getName()), ReplacementUtils.createSetVariableString(HostSetupNetworksValidator.VAR_NETWORK_NAME, networkA.getName()))); }
Source:
public void onItemClick(int position) { Intent intent = new Intent(this, ListActivity.class); String listName = nameListsAdapter.getItem(position); intent.putExtra(LIST_NAME_KEY, listName); intent.putExtra(LIST_TYPE, NAME_CHOOSING_FRAGMENT); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent); }

Target:
public void onItemClick(int position) { Intent intent = new Intent(this, ListActivity.class); String listName = nameListsAdapter.getItem(position); intent.putExtra(LIST_NAME_KEY, listName); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent); }
Source:
public void testGetListTrialSummariesBadSorterOrder() throws Exception { UriComponents uriComponents = UriComponentsBuilder.newInstance().path("/maize/brapi/v1/trials") .queryParam("programDbId", 1).queryParam("pageSize", 10) .queryParam("pageNumber", 1) .queryParam("sortOrder", "Ascendin").build().encode(); this.mockMvc.perform(MockMvcRequestBuilders.get(uriComponents.toUriString()).contentType(this.contentType)) .andExpect(MockMvcResultMatchers.status().isNotFound()) .andDo(MockMvcResultHandlers.print()).andExpect(jsonPath("$.metadata.status.message", is("sortOrder bad filter, expect Ascending/Descending"))) ; }

Target:
public void testGetListTrialSummariesBadSorterOrder() throws Exception { UriComponents uriComponents = UriComponentsBuilder.newInstance().path("/maize/brapi/v1/trials") .queryParam("programDbId", 1).queryParam("pageSize", 10) .queryParam("pageNumber", 1) .queryParam("sortOrder", "invalid_sort_order").build().encode(); this.mockMvc.perform(MockMvcRequestBuilders.get(uriComponents.toUriString()).contentType(this.contentType)) .andExpect(MockMvcResultMatchers.status().isNotFound()) .andDo(MockMvcResultHandlers.print()).andExpect(jsonPath("$.metadata.status.message", is("sortOrder bad filter, expect asc/desc"))) ; }
Source:
protected AbstractContentStore( ContentHasher hasher, IdGenerator idGenerator, MessageSender<ResourceUpdatedMessage> sender, EquivalenceGraphStore graphStore, Clock clock, MetricRegistry metricRegistry, String metricPrefix ) { this.hasher = checkNotNull(hasher); this.idGenerator = checkNotNull(idGenerator); this.sender = checkNotNull(sender); this.graphStore = checkNotNull(graphStore); this.clock = checkNotNull(clock); this.writingVisitor = new ContentWritingVisitor(); this.metricRegistry = metricRegistry; writeContent = metricPrefix + "writeContent"; writeBroadcast = metricPrefix + "writeBroadcast"; visit = metricPrefix + "visit"; }

Target:
protected AbstractContentStore( ContentHasher hasher, IdGenerator idGenerator, MessageSender<ResourceUpdatedMessage> sender, EquivalenceGraphStore graphStore, Clock clock, MetricRegistry metricRegistry, String metricPrefix ) { this.hasher = checkNotNull(hasher); this.idGenerator = checkNotNull(idGenerator); this.sender = checkNotNull(sender); this.graphStore = checkNotNull(graphStore); this.clock = checkNotNull(clock); this.writingVisitor = new ContentWritingVisitor(); this.metricRegistry = metricRegistry; writeContent = metricPrefix + "writeContent."; writeBroadcast = metricPrefix + "writeBroadcast."; visitMeterPrefix = metricPrefix + "visitMeterPrefix"; }
Source:
public IndexedSeq<Character> scan(Character zero, BiFunction<? super Character, ? super Character, ? extends Character> operation) { return Collections.scanLeft(this, zero, operation, Iterator::toCharSeq); }

Target:
public CharSeq scan(Character zero, BiFunction<? super Character, ? super Character, ? extends Character> operation) { return Collections.scanLeft(this, zero, operation, Iterator::toCharSeq); }
Source:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); results.disconnect(); } catch (IOException e) { throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).entity("Service Unavailable, IO Exception with Search Engine").build()); } }

Target:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); } catch (IOException e) { throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).entity("Service Unavailable, IO Exception with Search Engine").build()); } finally { results.disconnect(); } }
Source:
public Response installExtension( final @PathParam("extensionId") @ApiParam(value = "extension ID", required = true) String extensionId) { Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { extensionService.install(extensionId); postInstalledEvent(extensionId); } catch (Exception e) { logger.error("Exception while installing extension: {}", e.getMessage()); postFailureEvent(extensionId, e.getMessage()); } } }); return Response.ok().build(); }

Target:
public Response installExtension( final @PathParam("extensionId") @ApiParam(value = "extension ID", required = true) String extensionId) { ThreadPoolManager.getPool(THREAD_POOL_NAME).submit(new Runnable() { @Override public void run() { try { extensionService.install(extensionId); postInstalledEvent(extensionId); } catch (Exception e) { logger.error("Exception while installing extension: {}", e.getMessage()); postFailureEvent(extensionId, e.getMessage()); } } }); return Response.ok().build(); }
Source:
public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; } else if (teamText.hasFocus() == true) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }

Target:
public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; } else if (teamText.hasFocus()) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }
Source:
@Test public void queryMapToOneOrDefaultEmpty() { Employee employees = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES + " WHERE 1=2") .mapToOneOrDefault(Employee.MAPPER, null) .toBlocking() .first(); assertThat(employees).isNull(); }

Target:
@Test public void queryMapToOneOrDefaultEmpty() { Employee employees = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES + " WHERE 1=2") .mapToOneOrDefault(Employee.MAPPER, new Employee("bob", "Bob Bobberson")) .toBlocking() .first(); assertThat(employees).isEqualTo(new Employee("bob", "Bob Bobberson")); }
Source:
public HttpContent readChunk(ByteBufAllocator allocator) throws Exception { long chunkDispenseStartTime = System.currentTimeMillis(); logger.trace("Servicing request for next chunk on channel {}", ctx.channel()); HttpContent content = null; Chunk chunk = chunksToWrite.poll(); if (chunk != null) { chunk.onDequeue(); progress.addAndGet(chunk.buffer.readableBytes()); chunksAwaitingCallback.add(chunk); if (chunk.isLast) { content = new DefaultLastHttpContent(chunk.buffer); sentLastChunk = true; } else { content = new DefaultHttpContent(chunk.buffer); } } else if (allChunksWritten() && !sentLastChunk) { sentLastChunk = true; content = LastHttpContent.EMPTY_LAST_CONTENT; logger.trace("Last chunk was sent on channel {}", ctx.channel()); } nettyMetrics.chunkDispenseTimeInMs.update(System.currentTimeMillis() - chunkDispenseStartTime); return content; }

Target:
public HttpContent readChunk(ByteBufAllocator allocator) throws Exception { long chunkDispenseStartTime = System.currentTimeMillis(); logger.trace("Servicing request for next chunk on channel {}", ctx.channel()); HttpContent content = null; Chunk chunk = chunksToWrite.poll(); if (chunk != null) { chunk.onDequeue(); progress.addAndGet(chunk.buffer.readableBytes()); chunksAwaitingCallback.add(chunk); if (chunk.isLast) { content = new DefaultLastHttpContent(chunk.buffer.retainedDuplicate()); sentLastChunk = true; } else { content = new DefaultHttpContent(chunk.buffer.retainedDuplicate()); } } else if (allChunksWritten() && !sentLastChunk) { sentLastChunk = true; content = LastHttpContent.EMPTY_LAST_CONTENT; logger.trace("Last chunk was sent on channel {}", ctx.channel()); } nettyMetrics.chunkDispenseTimeInMs.update(System.currentTimeMillis() - chunkDispenseStartTime); return content; }
Source:
public static OverridePolicy get(String aLiteral) { for (OverridePolicy element : ENUM_ARRAY) { if (element.getLiteral().equals(aLiteral)) { return element; } } return InvokeAlwaysRegardlessOfSuppressedExt; }

Target:
public static OverridePolicy get(String aLiteral) { for (OverridePolicy policy : ENUM_ARRAY) { if (policy.getLiteral().equals(aLiteral)) { return policy; } } return InvokeAlwaysRegardlessOfSuppressedExt; }
Source:
protected boolean isConnectorIsOnPool(final Connector connector) { if (connector.eContainer() instanceof Pool) { return true; } return false; }

Target:
protected boolean isConnectorIsOnPool(final Connector connector) { return connector.eContainer() instanceof Pool; }
Source:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; if (language == "ja") { mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; }

Target:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; if (language.equals("ja")) { mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; }
Source:
public void testInvalidConfig() throws Exception { String inputTable = "input-xpath-with-multiple-elements"; ETLStage source = new ETLStage("source", MockSource.getPlugin(inputTable)); Map<String, String> sourceProperties = new ImmutableMap.Builder<String, String>() .put("input", "body") .put("encoding", "UTF-8") .put("xpathMappings", "category://book/@category,title://book/title,year:/bookstore/book[price>35.00]/year," + "price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory") .put("fieldTypeMapping", "category:,title:string,price:double,year:int,subcategory:string") .put("processOnError", "Exit on error") .build(); ETLStage transform = new ETLStage("transform", new ETLPlugin("XMLParser", Transform.PLUGIN_TYPE, sourceProperties, null)); String sinkTable = "output-xpath-with-multiple-elements"; ETLStage sink = new ETLStage("sink", MockSink.getPlugin(sinkTable)); ETLBatchConfig etlConfig = ETLBatchConfig.builder("* * * * *") .addStage(source) .addStage(transform) .addStage(sink) .addConnection(source.getName(), transform.getName()) .addConnection(transform.getName(), sink.getName()) .build(); AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(ETLBATCH_ARTIFACT, etlConfig); ApplicationId appId = NamespaceId.DEFAULT.app("XMLReaderTest"); try { deployApplication(appId.toId(), appRequest); Assert.fail(); } catch (IllegalStateException e) { } }

Target:
public void testInvalidConfig() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "category://book/@category,title://book/title," + "year:/bookstore/book[price>35.00]/year,price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory", "category:,title:string,price:double,year:int,subcategory:string", "Exit on error"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(INPUT); try { new XMLParser(config).configurePipeline(configurer); Assert.fail(); } catch (IllegalArgumentException e) { Assert.assertEquals("Type cannot be null. Please specify type for category", e.getMessage()); } }
Source:
private void alterTableDropPartition(TableWriter writer) throws SqlException { CharSequence tok = expectToken(lexer, "'list' or 'where'"); if (SqlKeywords.isListKeyword(tok)) { alterTableDropPartitionByList(writer); } else if (SqlKeywords.isWhereKeyword(tok)) { ExpressionNode expr = parser.expr(lexer, (QueryModel) null); int timestampIndex = writer.getMetadata().getTimestampIndex(); if (timestampIndex != -1) { String timestampColumnName = writer.getMetadata().getColumnName(timestampIndex); Function function = functionParser.parseFunction(expr, new SingleTimestampColumnRecordMetadata(timestampColumnName), currentExecutionContext); if (function != null && function.getType() == ColumnType.BOOLEAN) { writer.removePartition(function); } else { throw SqlException.$(lexer.lastTokenPosition(), "boolean expression expected"); } } } else { throw SqlException.$(lexer.lastTokenPosition(), "'list' or 'where' expected"); } }

Target:
private void alterTableDropPartition(TableWriter writer) throws SqlException { CharSequence tok = expectToken(lexer, "'list' or 'where'"); if (SqlKeywords.isListKeyword(tok)) { alterTableDropPartitionByList(writer); } else if (SqlKeywords.isWhereKeyword(tok)) { ExpressionNode expr = parser.expr(lexer, (QueryModel) null); String designatedTimestampColumnName = writer.getDesignatedTimestampColumnName(); if (designatedTimestampColumnName != null) { GenericRecordMetadata metadata = new GenericRecordMetadata(); metadata.add(new TableColumnMetadata(designatedTimestampColumnName, ColumnType.TIMESTAMP)); Function function = functionParser.parseFunction(expr, metadata, currentExecutionContext); if (function != null && function.getType() == ColumnType.BOOLEAN) { writer.removePartition(function); } else { throw SqlException.$(lexer.lastTokenPosition(), "boolean expression expected"); } } else { throw SqlException.$(lexer.lastTokenPosition(), "this table does not have a designated timestamp column"); } } else { throw SqlException.$(lexer.lastTokenPosition(), "'list' or 'where' expected"); } }
Source:
private Set<String> getDefaultAllowedOrigins() throws ServletException { GetDefaultAllowedOriginsQueryParameters parameters = new GetDefaultAllowedOriginsQueryParameters(); parameters.addSuffixes(defaultOriginsSuffixes); VdcQueryReturnValue value = backend.runPublicQuery(VdcQueryType.GetDefaultAllowedOrigins, parameters); if (!value.getSucceeded()) { throw new ServletException("Can't get list of default origins"); } log.debug("Origins allowed by default: {}", StringUtils.join((Set<String>)value.getReturnValue(), ',')); return value.getReturnValue(); }

Target:
private Set<String> getDefaultAllowedOrigins() throws ServletException { GetDefaultAllowedOriginsQueryParameters parameters = new GetDefaultAllowedOriginsQueryParameters(); parameters.addSuffixes(defaultOriginsSuffixes); VdcQueryReturnValue value = backend.runPublicQuery(VdcQueryType.GetDefaultAllowedOrigins, parameters); if (!value.getSucceeded()) { throw new ServletException("Can't get list of default origins"); } if (log.isDebugEnabled()) { log.debug("Origins allowed by default: {}", StringUtils.join((Set<String>) value.getReturnValue(), ',')); } return value.getReturnValue(); }
Source:
public static K parseWithDef(CharSequence theTextToParse, String mainModule, String startSymbol, org.kframework.kore.outer.Definition definition) { Module kastModule = definition.getModule(mainModule).get(); Grammar kastGrammar = KSyntax2GrammarStatesFilter.getGrammar(kastModule); Parser parser = new Parser(theTextToParse); Term parsed = parser.parse(kastGrammar.get(startSymbol), 0); if (parsed.equals(Ambiguity.apply())) { Parser.ParseError errors = parser.getErrors(); throw new AssertionError("There are parsing errors: " + errors.toString()); } Term cleaned = new TreeCleanerVisitor().apply(parsed); cleaned = new PreferAvoidVisitor().apply(cleaned); cleaned = new PriorityVisitor(kastModule.priorities(), kastModule.leftAssoc(), kastModule.rightAssoc()).apply(cleaned); return TreeNodesToKORE.apply(cleaned); }

Target:
public static K parseWithDef(CharSequence theTextToParse, String mainModule, String startSymbol, org.kframework.kore.outer.Definition definition) { Module kastModule = definition.getModule(mainModule).get(); Grammar kastGrammar = KSyntax2GrammarStatesFilter.getGrammar(kastModule); return parseWithGrammar(theTextToParse, startSymbol, kastModule, kastGrammar); }
Source:
public String templateCommand(TemplateEngine templateEngine, Config params, String aliasKey, Charset fileCharset) { if (params.has("_command")) { Config nested; try { nested = params.getNested("_command"); } catch (ConfigException notNested) { String command = params.get("_command", String.class); try { return templateFile(templateEngine, command, fileCharset, params); } catch (ConfigException ex) { throw ex; } catch (TemplateException ex) { throw new ConfigException("" + ex.getMessage() + " in " + command, ex); } catch (FileNotFoundException | NoSuchFileException ex) { throw new ConfigException("File not found: " + ex.getMessage(), ex); } catch (IOException ex) { throw new ConfigException("Failed to read a template file: " + command + ": " + ex.getClass(), ex); } catch (RuntimeException ex) { throw new ConfigException("" + ex.getMessage() + ": " + command, ex); } } return nested.get("data", String.class); } else if (aliasKey != null) { return params.get(aliasKey, String.class); } else { return params.get("_command", String.class); } }

Target:
public String templateCommand(TemplateEngine templateEngine, Config params, String aliasKey, Charset fileCharset) { if (params.has("_command")) { Config nested; try { nested = params.getNested("_command"); } catch (ConfigException notNested) { String fileName = params.get("_command", String.class); try { return templateFile(templateEngine, fileName, fileCharset, params); } catch (ConfigException ex) { throw ex; } catch (TemplateException ex) { throw new ConfigException( String.format(ENGLISH, "%s in %s", ex.getMessage(), fileName), ex); } catch (FileNotFoundException | NoSuchFileException ex) { throw new ConfigException( String.format(ENGLISH, "File not found: %s", ex.getMessage()), ex); } catch (IOException ex) { throw new ConfigException( String.format(ENGLISH, "Failed to read a template file: %s: %s", fileName, ex.getClass()), ex); } catch (RuntimeException ex) { throw new ConfigException( String.format(ENGLISH, "%s: %s", ex.getMessage(), fileName), ex); } } return nested.get("data", String.class); } else if (aliasKey != null) { return params.get(aliasKey, String.class); } else { return params.get("_command", String.class); } }
Source:
private boolean orchestrateDeleteVMSnapshot(Long vmSnapshotId) { Account caller = getCaller(); VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); if (vmSnapshot == null) { throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId); } _accountMgr.checkAccess(caller, null, true, vmSnapshot); if (VMSnapshot.State.Ready != vmSnapshot.getState() && VMSnapshot.State.Expunging != vmSnapshot.getState() && VMSnapshot.State.Error != vmSnapshot.getState() && VMSnapshot.State.Allocated != vmSnapshot.getState()) { throw new InvalidParameterValueException("Can't delete the vm snapshotshot " + vmSnapshotId + " due to it is not in Created or Error, or Expunging State"); } if (hasActiveVMSnapshotTasks(vmSnapshot.getVmId())) { List<VMSnapshotVO> expungingSnapshots = _vmSnapshotDao.listByInstanceId(vmSnapshot.getVmId(), VMSnapshot.State.Expunging); if (expungingSnapshots.size() > 0 && expungingSnapshots.get(0).getId() == vmSnapshot.getId()) s_logger.debug("Target VM snapshot already in expunging state, go on deleting it: " + vmSnapshot.getDisplayName()); else throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later"); } if (vmSnapshot.getState() == VMSnapshot.State.Allocated) { return _vmSnapshotDao.remove(vmSnapshot.getId()); } else { try { VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshot); return strategy.deleteVMSnapshot(vmSnapshot); } catch (Exception e) { s_logger.debug("Failed to delete vm snapshot: " + vmSnapshotId, e); return false; } } }

Target:
private boolean orchestrateDeleteVMSnapshot(Long vmSnapshotId) { Account caller = getCaller(); VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); if (vmSnapshot == null) { throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId); } _accountMgr.checkAccess(caller, null, true, vmSnapshot); List<VMSnapshot.State> validStates = Arrays.asList(VMSnapshot.State.Ready, VMSnapshot.State.Expunging, VMSnapshot.State.Error, VMSnapshot.State.Allocated); if (!validStates.contains(vmSnapshot.getState())) { throw new InvalidParameterValueException("Can't delete the vm snapshot " + vmSnapshotId + " due to it is not in " + validStates.toString() + "States"); } if (hasActiveVMSnapshotTasks(vmSnapshot.getVmId())) { List<VMSnapshotVO> expungingSnapshots = _vmSnapshotDao.listByInstanceId(vmSnapshot.getVmId(), VMSnapshot.State.Expunging); if (expungingSnapshots.size() > 0 && expungingSnapshots.get(0).getId() == vmSnapshot.getId()) s_logger.debug("Target VM snapshot already in expunging state, go on deleting it: " + vmSnapshot.getDisplayName()); else throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later"); } if (vmSnapshot.getState() == VMSnapshot.State.Allocated) { return _vmSnapshotDao.remove(vmSnapshot.getId()); } else { try { VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshot); return strategy.deleteVMSnapshot(vmSnapshot); } catch (Exception e) { s_logger.debug("Failed to delete vm snapshot: " + vmSnapshotId, e); return false; } } }
Source:
private static boolean classHasInheritance(PyClassDefTree classDef) { PyArgListTree args = classDef.args(); if(args == null) { return false; } List<Tree> children = args.children(); if(children.isEmpty()) { return false; } return children.size() != 1 || !"object".equals(children.get(0).firstToken().getValue()); }

Target:
private static boolean classHasInheritance(PyClassDefTree classDef) { PyArgListTree argList = classDef.args(); if (argList == null) { return false; } List<PyArgumentTree> arguments = argList.arguments(); if (arguments.isEmpty()) { return false; } return arguments.size() != 1 || !"object".equals(arguments.get(0).firstToken().getValue()); }