auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<CommandType> getCommandTypes(long deviceId, boolean sms) { List<CommandType> result = new ArrayList<>(); Position lastPosition = Context.getDeviceManager().getLastPosition(deviceId); if (lastPosition != null) { Collection<String> commands; if (sms) { commands = Context.getServerManager().getProtocol(lastPosition.getProtocol()).getSupportedSmsCommands(); } else { commands = Context.getServerManager().getProtocol(lastPosition.getProtocol()).getSupportedCommands(); } for (String commandKey : commands) { result.add(new CommandType(commandKey)); } } else { result.add(new CommandType(Command.TYPE_CUSTOM)); } return result; }

Target:
public Collection<CommandType> getCommandTypes(long deviceId, boolean sms) { List<CommandType> result = new ArrayList<>(); Position lastPosition = Context.getDeviceManager().getLastPosition(deviceId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); Collection<String> commands; commands = sms ? protocol.getSupportedSmsCommands() : protocol.getSupportedCommands(); for (String commandKey : commands) { result.add(new CommandType(commandKey)); } } else { result.add(new CommandType(Command.TYPE_CUSTOM)); } return result; }
Source:
protected void verifyOutput(ProductContent source, ProductContentDTO dto, boolean childrenGenerated) { if (source != null) { assertEquals(source.isEnabled(), dto.getEnabled()); if (childrenGenerated) { Content content = source.getContent(); ContentDTO contentDto = dto.getContent(); assertEquals(content.getUuid(), contentDto.getUuid()); assertEquals(content.getId(), contentDto.getId()); assertEquals(content.getType(), contentDto.getType()); assertEquals(content.getLabel(), contentDto.getLabel()); assertEquals(content.getName(), contentDto.getName()); assertEquals(content.getVendor(), contentDto.getVendor()); assertEquals(content.getContentUrl(), contentDto.getContentUrl()); assertEquals(content.getRequiredTags(), contentDto.getRequiredTags()); assertEquals(content.getReleaseVersion(), contentDto.getReleaseVer()); assertEquals(content.getGpgUrl(), contentDto.getGpgUrl()); assertEquals(content.getMetadataExpiration(), contentDto.getMetadataExpire()); assertEquals(content.getModifiedProductIds(), contentDto.getModifiedProductIds()); assertEquals(content.getArches(), contentDto.getArches()); } } else { assertNull(dto); } }

Target:
protected void verifyOutput(ProductContent source, ProductContentDTO dto, boolean childrenGenerated) { if (source != null) { assertEquals(source.isEnabled(), dto.getEnabled()); if (childrenGenerated) { this.contentTranslatorTest.verifyOutput( source.getContent(), dto.getContent(), childrenGenerated); } } else { assertNull(dto); } }
Source:
public void setBaseIri(String baseIri) { if (baseIri == null) return; this.baseIri = baseIri; }

Target:
public void setBaseIri(String baseIri) { Validate.notNull(baseIri); this.baseIri = baseIri; }
Source:
public final boolean breakpointDisabled( @Cached("breakpoint.getAssumption()") final Assumption bpUnchanged) { return ActivityThread.isSteppingType(breakpoint.getSteppingType()); }

Target:
public final boolean breakpointDisabled( @Cached("breakpoint.getAssumption()") final Assumption bpUnchanged) { return breakpoint.getSteppingType().isSet(); }
Source:
protected TestOrder cloneForRevisionHelper(TestOrder target) { super.cloneForRevisionHelper(target); target.setSpecimenSource(getSpecimenSource()); target.setLaterality(getLaterality()); target.setClinicalHistory(getClinicalHistory()); target.setFrequency(getFrequency()); target.setNumberOfRepeats(getNumberOfRepeats()); target.setOrderGroup(getOrderGroup()); target.setSortWeight(getSortWeight()); return target; }

Target:
protected TestOrder cloneForRevisionHelper(TestOrder target) { super.cloneForRevisionHelper(target); target.setSpecimenSource(getSpecimenSource()); target.setLaterality(getLaterality()); target.setClinicalHistory(getClinicalHistory()); target.setFrequency(getFrequency()); target.setNumberOfRepeats(getNumberOfRepeats()); return target; }
Source:
public FluoConfiguration setApplicationName(String applicationName) { return setNonEmptyString(CLIENT_APPLICATION_NAME_PROP, applicationName); }

Target:
public FluoConfiguration setApplicationName(String applicationName) { verifyApplicationName(applicationName); setProperty(CLIENT_APPLICATION_NAME_PROP, applicationName); return this; }
Source:
protected void executeQueryCommand() { List<VmTemplate> returnValue = DbFacade.getInstance() .getVmTemplateDao() .getAllForStorageDomain(getParameters().getId(), getUserID(), getParameters().isFiltered()); for (VmTemplate template : returnValue) { VmTemplateHandler.updateDisksFromDb(template); Collections.sort(template.getDiskList(), new DiskByDiskAliasComparator()); } Collections.sort(returnValue, Collections.reverseOrder(new VmTemplateComparerByDiskSize())); getQueryReturnValue().setReturnValue(returnValue); }

Target:
protected void executeQueryCommand() { List<VmTemplate> returnValue = DbFacade.getInstance() .getVmTemplateDao() .getAllForStorageDomain(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (getParameters().isWithDisks()) { for (VmTemplate template : returnValue) { VmTemplateHandler.updateDisksFromDb(template); Collections.sort(template.getDiskList(), new DiskByDiskAliasComparator()); } } Collections.sort(returnValue, Collections.reverseOrder(new VmTemplateComparerByDiskSize())); getQueryReturnValue().setReturnValue(returnValue); }
Source:
public void onLoadFinished(Loader<List<User>> listLoader, List<User> orgs) { this.orgs = orgs; orgListAdapter.setList(orgs); int sharedPreferencesOrgId = sharedPreferences.getInt(PREF_ORG_ID, -1); int targetOrgId = (org == null) ? sharedPreferencesOrgId : org.getId(); for (int i = 0; i < orgs.size(); ++i) { User availableOrg = orgs.get(i); if (availableOrg.getId() == targetOrgId) { getSupportActionBar().setSelectedNavigationItem(i); break; } } }

Target:
public void onLoadFinished(Loader<List<User>> listLoader, List<User> orgs) { this.orgs = orgs; orgListAdapter.setList(orgs); int sharedPreferencesOrgId = sharedPreferences.getInt(PREF_ORG_ID, -1); int targetOrgId = org == null ? sharedPreferencesOrgId : org.getId(); for (int i = 0; i < orgs.size(); ++i) { User availableOrg = orgs.get(i); if (availableOrg.getId() == targetOrgId) { getSupportActionBar().setSelectedNavigationItem(i); break; } } }
Source:
public void onClick(final View arg0) { if (requestTokenDialog == null) { requestTokenDialog = new ProgressDialog(TokenAuthorizationActivity.this); requestTokenDialog.setCancelable(false); requestTokenDialog.setMessage(getAuthDialogWait()); } requestTokenDialog.show(); startButton.setEnabled(false); startButton.setOnTouchListener(null); startButton.setOnClickListener(null); RxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { requestToken(usernameEditText.getText().toString(), passwordEditText.getText().toString()); } }); }

Target:
public void onClick(final View arg0) { if (requestTokenDialog == null) { requestTokenDialog = new ProgressDialog(TokenAuthorizationActivity.this); requestTokenDialog.setCancelable(false); requestTokenDialog.setMessage(getAuthDialogWait()); } requestTokenDialog.show(); startButton.setEnabled(false); startButton.setOnTouchListener(null); startButton.setOnClickListener(null); final String username = usernameEditText.getText().toString(); final String password = passwordEditText.getText().toString(); RxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { requestToken(username, password); } }); }
Source:
private void writeLine(String line) throws Exception { logger.debug("Sending request:'" + line + "'"); if (!isConnected()) { login(); } BufferedWriter writer; try { writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.write(line); writer.newLine(); writer.flush(); } catch (Exception e) { logger.debug("Could not write line. Disconnecting..., exception was: " + e); disconnect(); throw (e); } }

Target:
private void writeLine(String line) throws Exception { logger.debug("Sending request:'{}'", line); if (!isConnected()) { login(); } BufferedWriter writer; try { writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.write(line); writer.newLine(); writer.flush(); } catch (Exception e) { logger.debug("Could not write line. Disconnecting..., exception..", e); disconnect(); throw (e); } }
Source:
public void regressionTest() throws Exception { final Img<UnsignedByteType> image = openUnsignedByteType(getClass(), "lowresbridge.tif"); final Img<UnsignedByteType> expectedOutput = openUnsignedByteType( getClass(), "rotatedscaledcenter.tif"); final AffineTransform2D transform = new AffineTransform2D(); transform.translate(-image.dimension(0) / 2, -image.dimension(0) / 2); transform.rotate(1); transform.scale(0.5); transform.translate(image.dimension(0) / 2, image.dimension(0) / 2); final RandomAccessibleInterval<UnsignedByteType> actualOutput = ops .transform().realTransform(image, transform); final Cursor<UnsignedByteType> cursor = Views.iterable(actualOutput) .localizingCursor(); final RandomAccess<UnsignedByteType> actualRA = actualOutput.randomAccess(); final RandomAccess<UnsignedByteType> expectedRA = expectedOutput .randomAccess(); while (cursor.hasNext()) { cursor.fwd(); actualRA.setPosition(cursor); expectedRA.setPosition(cursor); assertEquals(expectedRA.get().get(), actualRA.get().get(), 0); } }

Target:
public void regressionTest() throws Exception { final Img<UnsignedByteType> image = openUnsignedByteType(getClass(), "lowresbridge.tif"); final Img<UnsignedByteType> expectedOutput = openUnsignedByteType( getClass(), "rotatedscaledcenter.tif"); final AffineTransform2D transform = new AffineTransform2D(); transform.translate(-image.dimension(0) / 2, -image.dimension(0) / 2); transform.rotate(1); transform.scale(0.5); transform.translate(image.dimension(0) / 2, image.dimension(0) / 2); @SuppressWarnings("unchecked") final RandomAccessibleInterval<UnsignedByteType> actualOutput = (RandomAccessibleInterval<UnsignedByteType>) ops.run( net.imagej.ops.transform.realTransform.DefaultTransformView.class, image, transform); final Cursor<UnsignedByteType> cursor = Views.iterable(actualOutput) .localizingCursor(); final RandomAccess<UnsignedByteType> actualRA = actualOutput.randomAccess(); final RandomAccess<UnsignedByteType> expectedRA = expectedOutput .randomAccess(); while (cursor.hasNext()) { cursor.fwd(); actualRA.setPosition(cursor); expectedRA.setPosition(cursor); assertEquals(expectedRA.get().get(), actualRA.get().get(), 0); } }
Source:
public void testIfColonPresentAtTheStartInUriCreds() { locator.setUri("http://:foobar@localhost:9999"); assertEquals("http://localhost:9999", locator.getRawUri()); assertEquals("user", locator.getUsername()); assertEquals("foobar", locator.getPassword()); }

Target:
public void testIfColonPresentAtTheStartInUriCreds() { locator.setUri("http://:foobar@localhost:9999"); assertEquals("http://localhost:9999", locator.getRawUri()); assertEquals("", locator.getUsername()); assertEquals("foobar", locator.getPassword()); }
Source:
protected void createDefaultEndStates(final Flow flow) { createRedirectUnauthorizedServiceUrlEndState(flow); createServiceErrorEndState(flow); createRedirectEndState(flow); createPostEndState(flow); createInjectHeadersActionState(flow); createGenericLoginSuccessEndState(flow); createServiceWarningViewState(flow); createMfaDeniedViewState(flow); createMfaUnavailableViewState(flow); createEndWebflowEndState(flow); }

Target:
protected void createDefaultEndStates(final Flow flow) { createRedirectUnauthorizedServiceUrlEndState(flow); createServiceErrorEndState(flow); createRedirectEndState(flow); createPostEndState(flow); createInjectHeadersActionState(flow); createGenericLoginSuccessEndState(flow); createServiceWarningViewState(flow); createEndWebflowEndState(flow); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); int size = args.getInt(ARG_SIZE); String message = args.getString(ARG_MESSAGE); messagingListener = new SimpleMessagingListener(){ @Override public void updateProgress(int progress) { updateDownloadProgress(progress); } }; MessagingController.getInstance(getActivity()).addDownloadProgressListener(messagingListener); dialog = new ProgressDialog(getActivity()); dialog.setMessage(message); dialog.setMax(size); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setProgress(0); dialog.show(); return dialog; }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); int size = args.getInt(ARG_SIZE); String message = args.getString(ARG_MESSAGE); progress = 0; messagingListener = new SimpleMessagingListener() { @Override public void updateProgress(int progress) { updateDownloadProgress(progress); } }; MessagingController.getInstance(getActivity()).addDownloadProgressListener(messagingListener); dialog = new ProgressDialog(getActivity()); dialog.setMessage(message); dialog.setMax(size); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setProgress(0); dialog.show(); return dialog; }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); if (hasHostExternalStatus()) { permissionList.add(new PermissionSubject(getParameters().getEvent().getVdsId(), VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); if (hasHostExternalStatus()) { permissionList.add(new PermissionSubject(getParameters().getEvent().getVdsId(), VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } if (hasStorageDomainExternalStatus()) { permissionList.add(new PermissionSubject(getParameters().getEvent().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.EDIT_STORAGE_DOMAIN_CONFIGURATION)); } return permissionList; }
Source:
protected boolean overlapInstant(Instant aStart, Instant aEnd, Instant bStart, Instant bEnd) { return (aStart.isBefore(bEnd) && bStart.isBefore(aEnd)); }

Target:
protected boolean overlapInstant(Instant aStart, Instant aEnd, Instant bStart, Instant bEnd) { return aStart.isBefore(bEnd) && bStart.isBefore(aEnd); }
Source:
public void testSortingNoSortMapping() throws Exception { expectedEx.expect(UnsupportedQueryException.class); expectedEx.expectMessage("Source WFS_ID does not support specified sort property title"); mapSchemaToFeatures(ONE_TEXT_PROPERTY_SCHEMA_PERSON, ONE_FEATURE); setUpMocks(null, null, ONE_FEATURE, ONE_FEATURE); final QueryImpl propertyIsLikeQuery = new QueryImpl(builder.attribute(Metacard.ANY_TEXT).is().like().text("literal")); setupMapper(null, null, null); source.setMetacardMappers(metacardMappers); source.setDisableSorting(false); propertyIsLikeQuery.setSortBy(new SortByImpl("title", SortOrder.ASCENDING)); final ArgumentCaptor<GetFeatureType> captor = ArgumentCaptor.forClass(GetFeatureType.class); source.query(new QueryRequestImpl(propertyIsLikeQuery)); }

Target:
public void testSortingNoSortMapping() throws Exception { expectedEx.expect(UnsupportedQueryException.class); expectedEx.expectMessage("Source WFS_ID does not support specified sort property title"); mapSchemaToFeatures(ONE_TEXT_PROPERTY_SCHEMA_PERSON, ONE_FEATURE); setUpMocks(null, null, ONE_FEATURE, ONE_FEATURE); final QueryImpl propertyIsLikeQuery = new QueryImpl(builder.attribute(Metacard.ANY_TEXT).is().like().text("literal")); setupMapper(null, null, null); source.setMetacardMappers(metacardMappers); source.setDisableSorting(false); propertyIsLikeQuery.setSortBy(new SortByImpl("title", SortOrder.ASCENDING)); source.query(new QueryRequestImpl(propertyIsLikeQuery)); }
Source:
public static Boolean isDefaultMaskPassword() { return null; }

Target:
public static Boolean isDefaultMaskPassword() { return DEFAULT_MASK_PASSWORD; }
Source:
public final Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { if (ctx.isOriginLocal() && !isLocalModeForced(command)) { if (!isSynchronous(command)) { rpcManager.sendToAll(command, DeliverOrder.PER_SENDER); return invokeNext(ctx, command); } else { RpcOptions rpcOptions = rpcManager.getSyncRpcOptions(); return asyncInvokeNext(ctx, command, rpcManager.invokeCommandOnAll(command, MapResponseCollector.ignoreLeavers(), rpcOptions)); } } return invokeNext(ctx, command); }

Target:
public final Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { if (ctx.isOriginLocal() && !isLocalModeForced(command)) { if (isSynchronous(command)) { RpcOptions rpcOptions = rpcManager.getSyncRpcOptions(); return asyncInvokeNext(ctx, command, rpcManager.invokeCommandOnAll(command, MapResponseCollector.ignoreLeavers(), rpcOptions)); } else { rpcManager.sendToAll(command, DeliverOrder.PER_SENDER); return invokeNext(ctx, command); } } return invokeNext(ctx, command); }
Source:
protected boolean verifySnapshotsStatus(List<Snapshot> snapshots) { for (Snapshot snapshot : snapshots) { if (snapshot.getStatus() != SnapshotStatus.OK && snapshot.getStatus() != SnapshotStatus.BROKEN) { return false; } } return true; }

Target:
protected boolean verifySnapshotsStatus(List<Snapshot> snapshots) { for (Snapshot snapshot : snapshots) { if (snapshot.getStatus() != SnapshotStatus.OK) { return false; } } return true; }
Source:
public void badAttributesSubgoal() { topLevelIngredient = new MashedPotatoes().topLevelIngredient; knowledgebase = new IngredientKnowledgebase(); allIngredients = knowledgebase.getPotentialIngredientObjectInstanceList(state, domain, topLevelIngredient); setUpState(); List<String> contents = Arrays.asList("butter", "potatoes", "salt", "eggs"); ObjectInstance mash = IngredientFactory.getNewComplexIngredientObjectInstance( domain.getObjectClass("complex_ingredient"), "Mashed_potatoes", Recipe.NO_ATTRIBUTES, Recipe.SWAPPED, "mixing_bowl_1", new TreeSet<String>(),new TreeSet<String>(), new TreeSet<String>(), contents); BakingAsserts.assertFailure(state, topLevelIngredient, mash); }

Target:
public void badAttributesSubgoal() { topLevelIngredient = new MashedPotatoes().topLevelIngredient; knowledgebase = new IngredientKnowledgebase(); allIngredients = knowledgebase.getPotentialIngredientObjectInstanceList(state, domain, topLevelIngredient); setUpState(); List<String> contents = Arrays.asList("butter", "potatoes", "salt", "eggs"); ObjectInstance mash = IngredientFactory.getNewComplexIngredientObjectInstance( domain.getObjectClass("complex_ingredient"), "Mashed_potatoes", Recipe.NO_ATTRIBUTES, Recipe.SWAPPED, "mixing_bowl_1", new HashSet<String>(),new HashSet<String>(), new HashSet<String>(), contents); BakingAsserts.assertFailure(state, topLevelIngredient, mash); }
Source:
public CourseAttributes(String courseId, String name, boolean archiveStatus) { id = Sanitizer.sanitizeTitle(courseId); this.name = Sanitizer.sanitizeTitle(name); isArchived = archiveStatus; }

Target:
public CourseAttributes(String courseId, String name, boolean archiveStatus) { this.id = Sanitizer.sanitizeTitle(courseId); this.name = Sanitizer.sanitizeTitle(name); this.isArchived = archiveStatus; }
Source:
public void nextPreviewStyle() { cyclePreview(Globals.prefs.getPreviewPreferences().getPreviewCyclePosition() + 1); }

Target:
public void nextPreviewStyle() { cyclePreview(preferences.getPreviewPreferences().getPreviewCyclePosition() + 1); }
Source:
public Builder withGender(GenderType gender) { profileAttributes.gender = isGenderValid(gender) ? gender : GenderType.other; return this; }

Target:
public Builder withGender(GenderType gender) { if (gender != null) { profileAttributes.gender = gender; } return this; }
Source:
public static synchronized void addToCache(AttestationValue value){ if (!attestationValues.containsKey(value.getHostName())) attestationValues.put(value.getHostName(), value); }

Target:
public static synchronized void addToCache(AttestationValue value){ if (!attestationValues.containsKey(value.getHostName())) attestationValues.putIfAbsent(value.getHostName(), value); }
Source:
private Set<BulkResult.BulkResultItem> retryOnlyIndexBlockItemsForever(List<Map.Entry<IndexSet, Message>> chunk, List<BulkResult.BulkResultItem> allFailedItems) { Set<BulkResult.BulkResultItem> indexBlocks = indexBlocksFrom(allFailedItems); Set<BulkResult.BulkResultItem> otherFailures = new HashSet<>(Sets.difference(new HashSet<>(allFailedItems), indexBlocks)); List<Map.Entry<IndexSet, Message>> blockedMessages = messagesForResultItems(chunk, indexBlocks); long attempt = 1; while (!indexBlocks.isEmpty()) { blockExecutionForAttempt(attempt++); BulkResult bulkResult = bulkIndexChunk(blockedMessages); List<BulkResult.BulkResultItem> failedItems = bulkResult.getFailedItems(); indexBlocks = indexBlocksFrom(failedItems); blockedMessages = messagesForResultItems(blockedMessages, indexBlocks); Set<BulkResult.BulkResultItem> newOtherFailures = Sets.difference(new HashSet<>(failedItems), indexBlocks); otherFailures.addAll(newOtherFailures); } return otherFailures; }

Target:
private Set<BulkResult.BulkResultItem> retryOnlyIndexBlockItemsForever(List<Map.Entry<IndexSet, Message>> chunk, List<BulkResult.BulkResultItem> allFailedItems) { Set<BulkResult.BulkResultItem> indexBlocks = indexBlocksFrom(allFailedItems); final Set<BulkResult.BulkResultItem> otherFailures = new HashSet<>(Sets.difference(new HashSet<>(allFailedItems), indexBlocks)); List<Map.Entry<IndexSet, Message>> blockedMessages = messagesForResultItems(chunk, indexBlocks); LOG.warn("Retrying messages, because their indices are blocked with status [read-only / allow delete]", indexBlocks.size()); long attempt = 1; while (!indexBlocks.isEmpty()) { waitBeforeRetrying(attempt++); final BulkResult bulkResult = bulkIndexChunk(blockedMessages); final List<BulkResult.BulkResultItem> failedItems = bulkResult.getFailedItems(); indexBlocks = indexBlocksFrom(failedItems); blockedMessages = messagesForResultItems(blockedMessages, indexBlocks); final Set<BulkResult.BulkResultItem> newOtherFailures = Sets.difference(new HashSet<>(failedItems), indexBlocks); otherFailures.addAll(newOtherFailures); if (indexBlocks.isEmpty()) { LOG.info("Retries were successful after attempts. Ingestion will continue now.", attempt); } } return otherFailures; }
Source:
public ReadOnlyBookie(ServerConfiguration conf, StatsLogger statsLogger) throws IOException, KeeperException, InterruptedException, BookieException { super(conf, statsLogger); stateManager = new BookieStateManager(bookieStatus, registrationManager){ @Override public void doTransitionToWritableMode() { LOG.info("Skip transition to writable mode for readonly bookie"); } @Override public void doTransitionToReadOnlyMode() { LOG.info("Skip transition to readonly mode for readonly bookie"); } }; if (conf.isReadOnlyModeEnabled()) { forceReadOnly.set(true); } else { String err = "Try to init ReadOnly Bookie, while ReadOnly mode is not enabled"; LOG.error(err); throw new IOException(err); } LOG.info("Running bookie in force readonly mode."); }

Target:
public ReadOnlyBookie(ServerConfiguration conf, StatsLogger statsLogger) throws IOException, KeeperException, InterruptedException, BookieException { super(conf, statsLogger); stateManager = new BookieStateManager(conf, statsLogger, registrationManager, getLedgerDirsManager()) { @Override public void doTransitionToWritableMode() { LOG.info("Skip transition to writable mode for readonly bookie"); } @Override public void doTransitionToReadOnlyMode() { LOG.info("Skip transition to readonly mode for readonly bookie"); } }; if (conf.isReadOnlyModeEnabled()) { stateManager.forceToReadOnly(); } else { String err = "Try to init ReadOnly Bookie, while ReadOnly mode is not enabled"; LOG.error(err); throw new IOException(err); } LOG.info("Running bookie in force readonly mode."); }
Source:
@Override public boolean active() { kernal.context().gateway().readLock(); try { return kernal.context().state().publicApiActiveState(true); } finally { kernal.context().gateway().readUnlock(); } }

Target:
@Override public boolean active() { return kernal.active(); }
Source:
public boolean syphonAndDamage(EntityPlayer user, SoulTicket ticket) { if (user.getEntityWorld().isRemote) return false; SoulNetworkEvent.Syphon.User event = new SoulNetworkEvent.Syphon.User(this, ticket, user); if (MinecraftForge.EVENT_BUS.post(event)) return false; int drainAmount = syphon(event.getTicket(), true); if (drainAmount <= 0 || event.shouldDamage()) hurtPlayer(user, event.getTicket().getAmount()); if (ticketHistory.contains(ticket)) ticketHistory.remove(ticket); ticketHistory.add(ticket); return BooleanResult.newResult(true, event.getTicket().getAmount()).isSuccess(); }

Target:
public BooleanResult<Integer> syphonAndDamage(EntityPlayer user, SoulTicket ticket) { if (user.getEntityWorld().isRemote) return BooleanResult.newResult(false, 0); SoulNetworkEvent.Syphon.User event = new SoulNetworkEvent.Syphon.User(this, ticket, user); if (MinecraftForge.EVENT_BUS.post(event)) return BooleanResult.newResult(false, 0); int drainAmount = syphon(event.getTicket(), true); if (drainAmount <= 0 || event.shouldDamage()) hurtPlayer(user, event.getTicket().getAmount()); if (ticketHistory.contains(ticket)) ticketHistory.remove(ticket); ticketHistory.add(ticket); return BooleanResult.newResult(true, event.getTicket().getAmount()); }
Source:
public String acceptCommand(String commandString) { if (commandString.startsWith(C5ServerConstants.START_META)) { HTableDescriptor metaDesc = HTableDescriptor.META_TABLEDESC; HRegionInfo metaRegion = new HRegionInfo( metaDesc.getTableName(), new byte[]{0}, new byte[]{}, false, 1); String peerString = commandString.substring(commandString.indexOf(":") + 1); List<Long> peers = new ArrayList<>(); for (String s : peerString.split(",")) { peers.add(new Long(s)); } openRegion0(metaRegion, metaDesc, ImmutableList.copyOf(peers), tabletRegistry); return "OK"; } else if (commandString.startsWith(C5ServerConstants.CREATE_TABLE)) { BASE64Decoder decoder = new BASE64Decoder(); String createString = commandString.substring(commandString.indexOf(":") + 1); String[] tableCreationStrings = createString.split(","); try { HTableDescriptor hTableDescriptor = HTableDescriptor.parseFrom(decoder.decodeBuffer(tableCreationStrings[0])); HRegionInfo hRegionInfo = HRegionInfo.parseFrom(decoder.decodeBuffer(tableCreationStrings[1])); List<Long> peers = new ArrayList<>(); for (String s : Arrays.copyOfRange(tableCreationStrings, 2, tableCreationStrings.length)) { s = StringUtils.strip(s); peers.add(new Long(s)); } openRegion0(hRegionInfo, hTableDescriptor, ImmutableList.copyOf(peers), tabletRegistry); return "OK"; } catch (IOException | DeserializationException e) { e.printStackTrace(); System.exit(0); } } return "NOTOK"; }

Target:
public String acceptCommand(String commandString) throws InterruptedException { if (commandString.startsWith(C5ServerConstants.START_META)) { HTableDescriptor metaDesc = HTableDescriptor.META_TABLEDESC; HRegionInfo metaRegion = new HRegionInfo( metaDesc.getTableName(), new byte[]{0}, new byte[]{}, false, 1); String peerString = commandString.substring(commandString.indexOf(":") + 1); List<Long> peers = new ArrayList<>(); for (String s : peerString.split(",")) { peers.add(new Long(s)); } try { openRegion0(metaRegion, metaDesc, ImmutableList.copyOf(peers)); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return "OK"; } else if (commandString.startsWith(C5ServerConstants.CREATE_TABLE)) { BASE64Decoder decoder = new BASE64Decoder(); String createString = commandString.substring(commandString.indexOf(":") + 1); String[] tableCreationStrings = createString.split(","); HTableDescriptor hTableDescriptor = null; try { hTableDescriptor = HTableDescriptor.parseFrom(decoder.decodeBuffer(tableCreationStrings[0])); HRegionInfo hRegionInfo = HRegionInfo.parseFrom(decoder.decodeBuffer(tableCreationStrings[1])); List<Long> peers = new ArrayList<>(); for (String s : Arrays.copyOfRange(tableCreationStrings, 2, tableCreationStrings.length)) { s = StringUtils.strip(s); peers.add(new Long(s)); } openRegion0(hRegionInfo, hTableDescriptor, ImmutableList.copyOf(peers)); } catch (IOException | DeserializationException e) { e.printStackTrace(); System.exit(1); } return "OK"; } return "NOTOK"; }
Source:
public void handleEvent(ITmfStateSystemBuilder ss, ITmfEvent event) throws AttributeNotFoundException { ITmfEventField content = event.getContent(); long ts = event.getTimestamp().getValue(); Integer sector = ((Long) content.getField(getLayout().fieldBlockSector()).getValue()).intValue(); Integer rqSector = ((Long) content.getField(getLayout().fieldBlockRqSector()).getValue()).intValue(); Integer nrSector = ((Long) content.getField(getLayout().fieldBlockNrSector()).getValue()).intValue(); Integer dev = ((Long) content.getField(getLayout().fieldBlockDeviceId()).getValue()).intValue(); Integer rwbs = ((Long) content.getField(getLayout().fieldBlockRwbs()).getValue()).intValue(); DiskWriteModel disk = fStateProvider.getDisk(dev); Request request = disk.getWaitingRequest(rqSector); if (request == null) { Bio bio = new Bio(rqSector, sector - rqSector, disk, rwbs); request = new Request(bio); } Bio bio = new Bio(sector, nrSector, disk, rwbs); request.insertBio(bio); disk.updateWaitingRequest(ts, request, rqSector); }

Target:
public void handleEvent(ITmfStateSystemBuilder ss, ITmfEvent event) throws AttributeNotFoundException { ITmfEventField content = event.getContent(); long ts = event.getTimestamp().getValue(); Long sector = NonNullUtils.checkNotNull((Long) content.getField(getLayout().fieldBlockSector()).getValue()); Long rqSector = NonNullUtils.checkNotNull((Long) content.getField(getLayout().fieldBlockRqSector()).getValue()); int nrSector = ((Long) content.getField(getLayout().fieldBlockNrSector()).getValue()).intValue(); int dev = ((Long) content.getField(getLayout().fieldBlockDeviceId()).getValue()).intValue(); int rwbs = ((Long) content.getField(getLayout().fieldBlockRwbs()).getValue()).intValue(); DiskWriteModel disk = fStateProvider.getDisk(dev); Request request = disk.getWaitingRequest(rqSector); if (request == null) { BlockIO bio = new BlockIO(rqSector, Long.valueOf(sector - rqSector).intValue(), disk, rwbs); request = new Request(bio); } BlockIO bio = new BlockIO(sector, nrSector, disk, rwbs); request.insertBio(bio); disk.updateWaitingRequest(ts, request, rqSector); }
Source:
public T put(String key, T value) { StorageEntry val = new StorageEntry(value.getClass().getName(), entityMapper.toJsonTree(value)); StorageEntry previousValue = map.get(key); map.put(key, val); deferredCommit(); if (previousValue == null) { return null; } return deserialize(previousValue); }

Target:
public T put(String key, T value) { StorageEntry val = new StorageEntry(value.getClass().getName(), entityMapper.toJsonTree(value)); StorageEntry previousValue = map.put(key, val); deferredCommit(); if (previousValue == null) { return null; } return deserialize(previousValue); }
Source:
private JvmConnectionWrapperLabelProvider findProvider(IActiveJvm jvm) { for( int i = 0; i < jvmConnectionLabelProviders.length; i++ ) { if( jvmConnectionLabelProviders[i].accepts(jvm)) return jvmConnectionLabelProviders[i]; } return null; }

Target:
private JVMLabelProviderDelegate findProvider(IActiveJvm jvm) { for( int i = 0; i < jvmConnectionLabelProviders.length; i++ ) { if( jvmConnectionLabelProviders[i].accepts(jvm)) return jvmConnectionLabelProviders[i]; } return null; }
Source:
private String getOutput() { int outputIndex = arguments.indexOf(toArg(IOptionKeys.OUTPUT)) + 1; String output = arguments.get(outputIndex); System.out.println(output); return String.valueOf(output); }

Target:
private String getOutput() { int index = arguments.indexOf(toArg(IOptionKeys.OUTPUT)) + 1; List<String> values = this.getValues(index); return values.size() == 1 ? values.get(0) : null; }
Source:
public static synchronized PrivateKey getRSAPrivateKey(String name, int length) { PrivateKey privateKey = null; createRSAKeys(name, length); try { KeyStore.Entry entry = loadKeyStore().getEntry(name, null); if (entry == null) { return null; } privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey(); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Security exception thrown", e); } return privateKey; }

Target:
public static synchronized PrivateKey getRSAPrivateKey(String name, int length) { PrivateKey privateKey = null; createRSAKeysIfNecessary(name, length); try { KeyStore.Entry entry = loadKeyStore().getEntry(name, null); if (entry == null) { return null; } privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey(); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Security exception thrown", e); } return privateKey; }
Source:
public void testMoreLikeThisOnEmbeddedFields() { boolean outputLogs = true; Transaction transaction = fullTextSession.beginTransaction(); Query mltQuery; List<Object[]> entityResults; try { QueryBuilder qb = getCoffeeQueryBuilder(); Coffee decaffInstance = getDecaffInstance( qb ); mltQuery = qb .moreLikeThis() .comparingField( "brand.name" ) .toEntityWithId( decaffInstance.getId() ) .createQuery(); entityResults = (List<Object[]>) fullTextSession .createFullTextQuery( mltQuery, Coffee.class ) .setProjection( ProjectionConstants.THIS, ProjectionConstants.SCORE ) .list(); assertThat( entityResults ).isNotEmpty(); Long matchingElements = (Long) fullTextSession.createQuery( "select count(*) from Coffee c where c.brand.name like '%pony'" ).uniqueResult(); assertThat( entityResults ).hasSize( matchingElements.intValue() ); float score = -1; for ( Object[] element : entityResults ) { if ( score == -1 ) { score = (Float) element[1]; } assertThat( element[1] ).as( "All scores should be equal as the same brand is used" ).isEqualTo( score ); } outputQueryAndResults( outputLogs, decaffInstance, mltQuery, entityResults ); } finally { transaction.commit(); } }

Target:
public void testMoreLikeThisOnEmbeddedFields() { boolean outputLogs = true; Transaction transaction = fullTextSession.beginTransaction(); Query mltQuery; List<Object[]> entityResults; try { QueryBuilder qb = getCoffeeQueryBuilder(); Coffee decaffInstance = getDecaffInstance( qb ); mltQuery = qb .moreLikeThis() .comparingField( "brand.name" ) .toEntityWithId( decaffInstance.getId() ) .createQuery(); entityResults = (List<Object[]>) fullTextSession .createFullTextQuery( mltQuery, Coffee.class ) .setProjection( ProjectionConstants.THIS, ProjectionConstants.SCORE ) .list(); assertThat( entityResults ).isNotEmpty(); Long matchingElements = (Long) fullTextSession.createQuery( "select count(*) from Coffee c where c.brand.name like '%pony'" ).uniqueResult(); assertThat( entityResults ).hasSize( matchingElements.intValue() ); float score = -1; for ( Object[] element : entityResults ) { if ( score == -1 ) { score = (Float) element[1]; } assertThat( element[1] ).as( "All scores should be equal as the same brand is used" ).isEqualTo( score ); } outputQueryAndResults( outputLogs, decaffInstance, mltQuery, entityResults ); try { qb .moreLikeThis() .comparingField( "brand.id" ) .toEntityWithId( decaffInstance.getId() ) .createQuery(); } catch (SearchException e) { assertThat( e.getMessage() ) .as( "Field cannot be used" ) .contains( "brand.id" ); } } finally { transaction.commit(); } }
Source:
public void testEnumObjectItems() { if (AbstractWin32TestSupport.isEnglishLocale) { String processorStr = "Process"; String processorTimeStr = "% Processor Time"; List<List<String>> objectItems = PdhUtil.PdhEnumObjectItems(null, null, processorStr, 100); List<String> counters = objectItems.get(0); List<String> instances = objectItems.get(1); assertTrue(instances.contains("0")); assertTrue(instances.contains("_Total")); assertTrue(counters.contains(processorTimeStr)); } else { System.err.println("testEnumObjectItems test can only be run with english locale."); } }

Target:
public void testEnumObjectItems() { if (AbstractWin32TestSupport.isEnglishLocale) { String processorStr = "Processor"; String processorTimeStr = "% Processor Time"; List<String> instances = PdhUtil.PdhEnumObjectItemInstances(null, null, processorStr, 100); assertTrue(instances.contains("0")); assertTrue(instances.contains("_Total")); List<String> counters = PdhUtil.PdhEnumObjectItemCounters(null, null, processorStr, 100); assertTrue(counters.contains(processorTimeStr)); } else { System.err.println("testEnumObjectItems test can only be run with english locale."); } }
Source:
private void loginSuccess(LoginResponse response) { fabProgressCircle.hide(); if (viewModel.isEditExisting()) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } else if (userManager.userExists(response.url, response.username)) { Snackbar.make(binding.getRoot(), R.string.login_account_error, Snackbar.LENGTH_LONG) .show(); } else { Account account = userManager.createUser(response.url, response.statusResponse.result.username, response.password, response.pwgId, response.statusResponse.result.pwgToken); userManager.setActiveAccount(account); setResultIntent(account); startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } }

Target:
private void loginSuccess(LoginResponse response) { fabProgressCircle.hide(); if (viewModel.isEditExisting()) { finish(); } else if (userManager.userExists(response.url, response.username)) { Snackbar.make(binding.getRoot(), R.string.login_account_error, Snackbar.LENGTH_LONG) .show(); } else { Account account = userManager.createUser(response.url, response.statusResponse.result.username, response.password, response.pwgId, response.statusResponse.result.pwgToken); userManager.setActiveAccount(account); setResultIntent(account); finish(); } }
Source:
public void resetPassword(PasswordReset passwordReset) { checkNotNull(passwordReset); String emailCacheKey = passwordReset.getSptoken() + ":email:" + passwordReset.getStudyIdentifier(); String phoneCacheKey = passwordReset.getSptoken() + ":phone:" + passwordReset.getStudyIdentifier(); String email = cacheProvider.getString(emailCacheKey); String phoneJson = cacheProvider.getString(phoneCacheKey); if (email == null && phoneJson == null) { throw new BadRequestException(PASSWORD_RESET_TOKEN_EXPIRED); } cacheProvider.removeString(emailCacheKey); cacheProvider.removeString(phoneCacheKey); Study study = studyService.getStudy(passwordReset.getStudyIdentifier()); AccountId accountId = null; if (email != null) { accountId = AccountId.forEmail(study.getIdentifier(), email); } else if (phoneJson != null) { accountId = AccountId.forPhone(study.getIdentifier(), getPhone(phoneJson)); } else { throw new BridgeServiceException("Could not reset password"); } Account account = accountDao.getAccount(accountId); if (account == null) { throw new EntityNotFoundException(Account.class); } accountDao.changePassword(account, passwordReset.getPassword()); }

Target:
public void resetPassword(PasswordReset passwordReset) { checkNotNull(passwordReset); String emailCacheKey = passwordReset.getSptoken() + ":" + passwordReset.getStudyIdentifier(); String phoneCacheKey = passwordReset.getSptoken() + ":phone:" + passwordReset.getStudyIdentifier(); String email = cacheProvider.getString(emailCacheKey); String phoneJson = cacheProvider.getString(phoneCacheKey); if (email == null && phoneJson == null) { throw new BadRequestException(PASSWORD_RESET_TOKEN_EXPIRED); } cacheProvider.removeString(emailCacheKey); cacheProvider.removeString(phoneCacheKey); Study study = studyService.getStudy(passwordReset.getStudyIdentifier()); AccountId accountId = null; if (email != null) { accountId = AccountId.forEmail(study.getIdentifier(), email); } else if (phoneJson != null) { accountId = AccountId.forPhone(study.getIdentifier(), getPhone(phoneJson)); } else { throw new BridgeServiceException("Could not reset password"); } Account account = accountDao.getAccount(accountId); if (account == null) { throw new EntityNotFoundException(Account.class); } accountDao.changePassword(account, passwordReset.getPassword()); }
Source:
protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException { Trade charge = getTrade(sign, 1, 2, player, ess); Trade money = getTrade(sign, 3, ess); if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { ItemStack heldItem = player.getItemInHand(); if (charge.getItemStack().isSimilar(heldItem)) { int initialItemAmount = charge.getItemStack().getAmount(); int newItemAmount = heldItem.getAmount(); ItemStack item = charge.getItemStack(); item.setAmount(newItemAmount); charge = new Trade(item, ess); BigDecimal chargeAmount = money.getMoney(); BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount), RoundingMode.HALF_EVEN); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); money = new Trade(pricePerSingleItem, ess); } } charge.isAffordableFor(player); money.pay(player, OverflowType.DROP); charge.charge(player); Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess); return true; }

Target:
protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException { Trade charge = getTrade(sign, 1, 2, player, ess); Trade money = getTrade(sign, 3, ess); if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { ItemStack heldItem = player.getItemInHand(); if (charge.getItemStack().isSimilar(heldItem)) { int initialItemAmount = charge.getItemStack().getAmount(); int newItemAmount = heldItem.getAmount(); ItemStack item = charge.getItemStack(); item.setAmount(newItemAmount); charge = new Trade(item, ess); BigDecimal chargeAmount = money.getMoney(); BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount)); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); money = new Trade(pricePerSingleItem, ess); } } charge.isAffordableFor(player); money.pay(player, OverflowType.DROP); charge.charge(player); Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess); return true; }
Source:
public synchronized PMML4Result submitRequest(PMMLRequestData request) throws InvalidParameterException, IllegalStateException { if (request == null) { throw new InvalidParameterException("PMML model cannot be applied to a null request"); } if (ruleUnitClass == null) { throw new IllegalStateException("PMML model cannot be applied. Missing ruleUnitClass."); } if (used) { used = false; initRuleUnitExecutor(); } KieRuntimeLogger logger = loggerFileName != null ? ((InternalRuleUnitExecutor)executor).addFileLogger(loggerFileName) : null; try { requestData.insert(request); baseResultHolder = new PMML4Result(request.getCorrelationId()); resultData.insert(baseResultHolder); executor.run(ruleUnitClass); } finally { if (logger != null) logger.close(); } used = true; return baseResultHolder; }

Target:
public synchronized PMML4Result submitRequest(PMMLRequestData request) throws InvalidParameterException, IllegalStateException { if (request == null) { throw new InvalidParameterException("PMML model cannot be applied to a null request"); } if (ruleUnitClass == null) { throw new IllegalStateException("PMML model cannot be applied. Missing ruleUnitClass."); } if (used) { used = false; initRuleUnitExecutor(); } KieRuntimeLogger logger = loggerFileName != null ? ((InternalRuleUnitExecutor)executor).addFileLogger(loggerFileName) : null; try { requestData.insert(request); baseResultHolder = new PMML4Result(request.getCorrelationId()); resultData.insert(baseResultHolder); executor.run(ruleUnitClass); } finally { if (logger != null) { logger.close(); } } used = true; return baseResultHolder; }
Source:
public <T> List<T> stores(final String storeName, final QueryableStoreType<T> queryableStoreType) { final List<T> allStores = new ArrayList<>(); for (final StreamThreadStateStoreProvider provider : storeProviders) { final List<T> stores = provider.stores(storeQueryParameters); if (stores != null && !stores.isEmpty()) { allStores.addAll(stores); } } if (allStores.isEmpty()) { throw new InvalidStateStoreException("The state store, " + storeName + ", may have migrated to another instance."); } return allStores; }

Target:
public <T> List<T> stores(final String storeName, final QueryableStoreType<T> queryableStoreType) { final List<T> allStores = new ArrayList<>(); for (final StreamThreadStateStoreProvider provider : storeProviders) { final List<T> stores = provider.stores(storeQueryParameters); allStores.addAll(stores); } if (allStores.isEmpty()) { throw new InvalidStateStoreException("The state store, " + storeName + ", may have migrated to another instance."); } return allStores; }
Source:
public void testAddModifiedBy() throws Exception { URL resource = PomIOTest.class.getResource( filename ); assertNotNull( resource ); File pom = new File( resource.getFile() ); assertTrue( pom.exists() ); File targetFile = folder.newFile( "target.xml" ); FileUtils.copyFile( pom, targetFile ); List<Project> projects = pomIO.parseProject( targetFile ); projects.get( 0 ).setExecutionRoot(); HashSet<Project> changed = new HashSet<>(); changed.add( projects.get( 0 ) ); pomIO.rewritePOMs( changed ); String s = FileUtils.readFileToString( targetFile, Charset.defaultCharset() ); assertEquals( StringUtils.countMatches(s, "Modified by POM Manipulation Extension" ), 1); pomIO.rewritePOMs( changed ); s = FileUtils.readFileToString( targetFile, Charset.defaultCharset() ); assertEquals( StringUtils.countMatches(s, "Modified by POM Manipulation Extension" ), 1); }

Target:
public void testAddModifiedBy() throws Exception { URL resource = PomIOTest.class.getResource( filename ); assertNotNull( resource ); File pom = new File( resource.getFile() ); assertTrue( pom.exists() ); File targetFile = folder.newFile( "target.xml" ); FileUtils.copyFile( pom, targetFile ); Project project = pomIO.parseProject( targetFile ).get( 0 ); project.setExecutionRoot(); HashSet<Project> changed = new HashSet<>(); changed.add( project ); pomIO.rewritePOMs( changed ); String s = FileUtils.readFileToString( targetFile, StandardCharsets.UTF_8 ); assertEquals( 1, StringUtils.countMatches(s, "Modified by POM Manipulation Extension" ) ); pomIO.rewritePOMs( changed ); s = FileUtils.readFileToString( targetFile, StandardCharsets.UTF_8 ); assertEquals( 1, StringUtils.countMatches(s, "Modified by POM Manipulation Extension" ) ); }