auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <T> Hits<T> search(Query<T> query) throws IOException { if (query.getFields() == null || query.getFields().isEmpty()) { return searchDefault(query); } if (!SortBy.DOC.equals(query.getSortBy())) { throw new IllegalArgumentException("Queries with field selection can't be sorted: " + query.getSortBy()); } return searchByCollector(query); }

Target:
public <T> Hits<T> search(Query<T> query) throws IOException { final QueryProfiler profiler = new QueryProfiler(query, slowLogConfig); final DocumentMapping mapping = getDocumentMapping(query); final org.apache.lucene.search.Query lq = toLuceneQuery(mapping, query); final org.apache.lucene.search.Sort ls = toLuceneSort(mapping, query); final int offset = query.getOffset(); int limit = query.getLimit(); try { profiler.start(Phase.QUERY); final TopFieldDocs topDocs; if (limit < 1) { final int totalHits = searcher.count(lq); topDocs = new TopFieldDocs(totalHits, null, null, 0); } else { if (limit == Integer.MAX_VALUE || limit == Integer.MAX_VALUE - 1 ) { limit = searcher.count(lq); } int maxDoc = searcher.getIndexReader().maxDoc(); if (maxDoc <= 0 || limit < 1) { topDocs = new TopFieldDocs(0, null, null, 0); } else { topDocs = searcher.search(lq, numDocsToRetrieve(offset, limit), ls, query.isWithScores(), false); } } profiler.end(Phase.QUERY); if (topDocs.scoreDocs == null || topDocs.scoreDocs.length < 1) { return new Hits<>(Collections.<T>emptyList(), offset, limit, topDocs.totalHits); } else { profiler.start(Phase.FETCH); final ImmutableList.Builder<T> matches = ImmutableList.builder(); if (query.getFields() != null && !query.getFields().isEmpty()) { fetchFieldDocs(query, mapping, offset, topDocs, matches); } else { fetchScoreDocs(query, mapping, offset, topDocs, matches); } profiler.end(Phase.FETCH); return new Hits<>(matches.build(), offset, limit, topDocs.totalHits); } } finally { profiler.log(log); } }
Source:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug(result.toString()); for (Entry<String, Object> values : result.getValues().entrySet()) { if (isNotValidValue(values.getValue())) { log.debug("Skipping message key[{}] with value: {}.", values.getKey(), values.getValue()); continue; } String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix); String replaceString = "_"; if (this.invalidCharValue != null){ replaceString = this.invalidCharValue; } line = STATSD_INVALID.matcher(line).replaceAll(replaceString); line += computeActualValue(values.getValue()) + "|" + bucketType + "\n"; doSend(line.trim()); } } }

Target:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug(result.toString()); for (Entry<String, Object> values : result.getValues().entrySet()) { if (isNotValidValue(values.getValue())) { log.debug("Skipping message key[{}] with value: {}.", values.getKey(), values.getValue()); continue; } String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix); line = STATSD_INVALID.matcher(line).replaceAll(this.replacementForInvalidChar); line += computeActualValue(values.getValue()) + "|" + bucketType + "\n"; doSend(line.trim()); } } }
Source:
public static java.util.Collection<Portlet> getPortlets(final java.lang.String companyId) throws com.liferay.portal.SystemException { try { final PortletFactory portletFactory = PortletManagerFactory.getManager(); return portletFactory.getPortlets(); } catch (final com.liferay.portal.SystemException se) { throw se; } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } }

Target:
public static java.util.Collection<Portlet> getPortlets(final java.lang.String companyId) throws com.liferay.portal.SystemException { try { final PortletFactory portletFactory = PortletManagerFactory.getManager(); return portletFactory.getPortlets(); } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } }
Source:
public float getLeftMargin(Actor actor) { for (Constraints c : constraints) { if (c.actor == actor) { return marginLeft(c); } } return -1; }

Target:
public float getLeftMargin(Actor actor) { for (Constraints c : constraints) { if (c.actor == actor) { return marginLeft(c); } } return 0; }
Source:
public static <A> PriorityQueue<Integer, A> emptyInt() { return priorityQueue(Equal.intEqual, FingerTree.empty(Monoid.intMaxMonoid, (P2<Integer, A> p) -> p._1())); }

Target:
public static <A> PriorityQueue<Integer, A> emptyInt() { return empty(Monoid.intMaxMonoid, Equal.intEqual); }
Source:
public synchronized void operationComplete(long operationSequenceId) { Long heapSize = pendingOperationsWithSize.remove(operationSequenceId); if (heapSize != null) { currentWriteBufferSize -= heapSize; notifyAll(); } else { LOG.warn("Something is wrong with BigtableBufferedMutator. Operation %s was not found", operationSequenceId); } }

Target:
public synchronized void operationComplete(long operationSequenceId) { lastOperationChange = System.currentTimeMillis(); Long heapSize = pendingOperationsWithSize.remove(operationSequenceId); if (heapSize != null) { currentWriteBufferSize -= heapSize; notifyAll(); } else { LOG.warn("An operation completion was recieved multiple times. Your operations completed." + " Please notify Google that this occurred."); } }
Source:
public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final String userParentSpan = "user-parent-span"; final String openCensusSpanKey = "opencensus-span"; final String hostName = "hostName-key"; final String entityPath = "entity-path-key"; Context parentSpanContext = new Context(openCensusSpanKey, userParentSpan); Context updatedContext = parentSpanContext.addData(hostName, hostNameValue) .addData(entityPath, entityPathValue); System.out.printf("HOSTNAME value: %s%n", updatedContext.getData(hostName).get()); System.out.printf("ENTITY_PATH value: %s%n", updatedContext.getData(entityPath).get()); END: com.azure.core.util.context.addData#object-object }

Target:
public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final String userParentSpan = "user-parent-span"; Context parentSpanContext = new Context(PARENT_SPAN_KEY, userParentSpan); Context updatedContext = parentSpanContext.addData(HOST_NAME_KEY, hostNameValue) .addData(ENTITY_PATH_KEY, entityPathValue); System.out.printf("Hostname value: %s%n", updatedContext.getData(HOST_NAME_KEY).get()); System.out.printf("Entity Path value: %s%n", updatedContext.getData(ENTITY_PATH_KEY).get()); END: com.azure.core.util.context.addData#object-object }
Source:
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "AzureCliCredential authentication unavailable.", t))); }

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithAzureCli(request); }
Source:
public void initializeDestinationForDatastream(Datastream datastream) { if (!datastream.hasDestination()) { datastream.setDestination(new DatastreamDestination()); } DatastreamDestination destination = datastream.getDestination(); DatastreamSource source = datastream.getSource(); if (!destination.hasConnectionString() || destination.getConnectionString().isEmpty()) { String topicName = getTopicName(datastream.getName()); destination.setConnectionString(getDestination(topicName)); destination.setConnectionString(getDestination(topicName)); } if (!destination.hasPartitions() || destination.getPartitions() <= 0) { if (source.hasPartitions()) { destination.setPartitions(source.getPartitions()); } else { destination.setPartitions(DEFAULT_NUMBER_PARTITIONS); } } }

Target:
public void initializeDestinationForDatastream(Datastream datastream) { if (!datastream.hasDestination()) { datastream.setDestination(new DatastreamDestination()); } DatastreamDestination destination = datastream.getDestination(); DatastreamSource source = datastream.getSource(); if (!destination.hasConnectionString() || destination.getConnectionString().isEmpty()) { String topicName = getTopicName(datastream.getName()); destination.setConnectionString(getDestination(topicName)); } if (!destination.hasPartitions() || destination.getPartitions() <= 0) { if (source.hasPartitions()) { destination.setPartitions(source.getPartitions()); } else { destination.setPartitions(DEFAULT_NUMBER_PARTITIONS); } } }
Source:
public void createArtifacts() { ArtifactId parentArtifact = CoreArtifactTokens.OseeTypesFolder; List<String> names = new ArrayList<>(); names.add("TestArtifact1"); names.add("TestArtifact2"); names.add("TestArtifact3"); List<ArtifactToken> newArtifacts = artifactEndpoint.createArtifacts(COMMON, CoreArtifactTypes.PlainText, parentArtifact, names); Assert.assertFalse(newArtifacts.isEmpty()); }

Target:
public void createArtifacts() { ArtifactId parentArtifact = CoreArtifactTokens.OseeTypesFolder; List<String> names = Arrays.asList("TestArtifact1", "TestArtifact2", "TestArtifact3"); List<ArtifactToken> newArtifacts = artifactEndpoint.createArtifacts(COMMON, CoreArtifactTypes.PlainText, parentArtifact, names); Assert.assertFalse(newArtifacts.isEmpty()); }
Source:
protected void afterRelease(MessageGroup messageGroup, Collection<Message<?>> completedMessages, boolean timeout) { int size = messageGroup.getMessages().size(); int sequenceSize = 0; Message<?> message = messageGroup.getOne(); if (message != null){ sequenceSize = new IntegrationMessageHeaderAccessor(message).getSequenceSize(); } if (sequenceSize > 0 && sequenceSize == size){ remove(messageGroup); } else { Object groupId = messageGroup.getGroupId(); if (completedMessages != null) { int lastReleasedSequenceNumber = findLastReleasedSequenceNumber(groupId, completedMessages); this.messageStore.setLastReleasedSequenceNumberForGroup(groupId, lastReleasedSequenceNumber); if (this.messageStore instanceof SimpleMessageStore && completedMessages.size() == messageGroup.size()) { ((SimpleMessageGroup) messageGroup).clear(); ((SimpleMessageGroup) messageGroup).setLastModified(System.currentTimeMillis()); } else { this.messageStore.removeMessagesFromGroup(groupId, completedMessages); } } if (timeout) { this.messageStore.completeGroup(groupId); } } }

Target:
protected void afterRelease(MessageGroup messageGroup, Collection<Message<?>> completedMessages, boolean timeout) { int size = messageGroup.getMessages().size(); int sequenceSize = 0; Message<?> message = messageGroup.getOne(); if (message != null){ sequenceSize = new IntegrationMessageHeaderAccessor(message).getSequenceSize(); } if (sequenceSize > 0 && sequenceSize == size){ remove(messageGroup); } else { Object groupId = messageGroup.getGroupId(); if (completedMessages != null) { int lastReleasedSequenceNumber = findLastReleasedSequenceNumber(groupId, completedMessages); this.messageStore.setLastReleasedSequenceNumberForGroup(groupId, lastReleasedSequenceNumber); if (this.messageStore instanceof SimpleMessageStore && completedMessages.size() == messageGroup.size()) { ((SimpleMessageStore) this.messageStore).clearMessageGroup(groupId); } else { this.messageStore.removeMessagesFromGroup(groupId, completedMessages); } } if (timeout) { this.messageStore.completeGroup(groupId); } } }
Source:
public void setImageGenResults(HashMap<String, View> viewMap, HashMap<String, Bitmap> imageMap) { mapboxMap.getStyle(new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { style.addImages(imageMap); SymbolLayerMapillaryActivity.this.viewMap = viewMap; } }); }

Target:
public void setImageGenResults(HashMap<String, View> viewMap, HashMap<String, Bitmap> imageMap) { mapboxMap.getStyle(new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { style.addImages(imageMap); } }); SymbolLayerMapillaryActivity.this.viewMap = viewMap; }
Source:
public void checkGroovyVersion(String whoIsChecking) { if (!isCompatibleGroovyVersion() && !isVersionCheckDisabled()) throw new IncompatibleGroovyVersionException(String.format( "The Spock %s cannot execute because Spock %s is not compatible with Groovy %s. For more information (including enforce mode), " + "see <LINK_0> (section 'Known Issues').\n" + "Spock artifact: %s\n" + "Groovy artifact: %s", whoIsChecking, SpockReleaseInfo.getVersion(), GroovyReleaseInfo.getVersion(), SpockReleaseInfo.getArtifactPath(), GroovyReleaseInfo.getArtifactPath())); }

Target:
public void checkGroovyVersion(String whoIsChecking) { if (!isCompatibleGroovyVersion()) { if (isVersionCheckDisabled()) { System.err.println(format("Executing Spock %s with NOT compatible Groovy version %s due to set %s system property set. " + "This is unsupported and may result in weird runtime errors!", SpockReleaseInfo.getVersion(), GroovyReleaseInfo.getVersion(), DISABLE_GROOVY_VERSION_CHECK_PROPERTY_NAME)); } else { throw new IncompatibleGroovyVersionException(format( "The Spock %s cannot execute because Spock %s is not compatible with Groovy %s. For more information (including enforce mode), " + "see <LINK_0> (section 'Known Issues').\n" + "Spock artifact: %s\n" + "Groovy artifact: %s", whoIsChecking, SpockReleaseInfo.getVersion(), GroovyReleaseInfo.getVersion(), SpockReleaseInfo.getArtifactPath(), GroovyReleaseInfo.getArtifactPath())); } } }
Source:
public List<String> getEnabledTemplates() { if (enabledTemplates == null) { return new ArrayList<>(); } return enabledTemplates; }

Target:
public List<String> getEnabledTemplates() { return enabledTemplates; }
Source:
public void testExecuteIgnoredModule() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final LocalizedMessage errorCounterMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "Main.errorCounter", new String[] {String.valueOf(1)}, null, getClass(), null); final String expectedExceptionMessage = String.format(Locale.ROOT, errorCounterMessage.getMessage() + "%n"); assertEquals(expectedExceptionMessage, systemOut.getLog()); final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:" + " cannot initialize module TreeWalker - "; assertTrue(systemErr.getLog().startsWith(cause)); }); Main.main("-c", getPath("config-non-existing-classname-ignore.xml"), "-executeIgnoredModules", getPath("InputMain.java")); }

Target:
public void testExecuteIgnoredModule() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String expectedExceptionMessage = errorCounterOneMessage.getMessage() + EOL; assertEquals(expectedExceptionMessage, systemOut.getLog()); final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:" + " cannot initialize module TreeWalker - "; assertTrue(systemErr.getLog().startsWith(cause)); }); Main.main("-c", getPath("config-non-existing-classname-ignore.xml"), "-executeIgnoredModules", getPath("InputMain.java")); }
Source:
@Override public Vector2i getSize() { return Vector2i.from(128, 128); }

Target:
public Vector2i getSize() { return Vector2i.from(128, 128); }
Source:
public void stepSetReverseModeAtLocation(final RequestMonitor rm) { MIBreakpoint bp = getBreakPointForReverse(); if (getReverseEnabled() && fReverseService != null && bp != null) { try { fReverseService.enableReverseModeAtBpLocation(getContainerContext(), getReverseMode(), bp, !getUserBreakpointIsOnMain()); rm.done(); } catch (CoreException e) { rm.done(e.getStatus()); } } else { rm.done(); } }

Target:
public void stepSetReverseModeAtLocation(final RequestMonitor rm) { MIBreakpoint bp = getBreakPointForReverse(); if (getReverseEnabled() && fReverseService != null && bp != null) { fReverseService.enableReverseModeAtBpLocation(getContainerContext(), getReverseMode(), bp, !getUserBreakpointIsOnMain()); rm.done(); } else { rm.done(); } }
Source:
public void inviteMember(Long teamId, String username) { User user = userService.getUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username)); Team team = getTeamById(teamId).orElseThrow(() -> new TeamNotFoundException(teamId)); String token = UUID.randomUUID().toString(); if (!team.getMembers().contains(user)) { TeamInviteToken inviteToken = new TeamInviteToken(token, user, team); teamInviteTokenRepository.save(inviteToken); try { mailService.sendTeamInviteMail(user, team.getTeamName()); } catch (MessagingException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("User is already a member of this team"); } }

Target:
public TeamInviteToken inviteMember(Long teamId, String username) { User user = userService.getUserByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username)); Team team = getTeamById(teamId); if (!team.getMembers().contains(user)) { String token = UUID.randomUUID().toString(); TeamInviteToken inviteToken = new TeamInviteToken(token, user, team); teamInviteTokenRepository.save(inviteToken); try { mailService.sendTeamInviteMail(user, team.getTeamName(), team.getCaptain()); } catch (MessagingException e) { e.printStackTrace(); } return inviteToken; } else { throw new IllegalArgumentException("User is already a member of this team"); } }
Source:
public void onEvent(MachineLogEvent event) { String stream = event.getStream(); String text = event.getText(); if (!isNullOrEmpty(stream) && "stderr".equalsIgnoreCase(stream) && !isNullOrEmpty(text)) { RuntimeIdentityDto identity = event.getRuntimeId(); LOG.error( "Machine error from owner={} env={} workspace={} text={} time={} ", event.getMachineName(), identity.getOwnerId(), identity.getEnvName(), identity.getWorkspaceId(), event.getText(), event.getTime()); } }

Target:
public void onEvent(MachineLogEvent event) { if ("stderr".equalsIgnoreCase(event.getStream()) && !isNullOrEmpty(event.getText())) { RuntimeIdentityDto identity = event.getRuntimeId(); LOG.error( "Machine `{}` error from owner=`{}` env=`{}` workspace=`{}` text=`{}` time=`{}`", event.getMachineName(), identity.getOwnerId(), identity.getEnvName(), identity.getWorkspaceId(), event.getText(), event.getTime()); } }
Source:
public static FetchedS3Object createS3Object() { FetchedS3Object result = new FetchedS3Object(null); result.setRelocated(true); return result; }

Target:
public static FetchedS3Object createS3Object() { val result = new FetchedS3Object(null); result.setRelocated(true); return result; }
Source:
public void init(@NonNull FrameLayout parent) { mTextureView = new TextureView(parent.getContext()); mTextureView.setLayoutParams( new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(final SurfaceTexture surfaceTexture, final int width, final int height) { mSurfaceTexture = surfaceTexture; tryToProvidePreviewSurface(); } @Override public void onSurfaceTextureSizeChanged(final SurfaceTexture surfaceTexture, final int width, final int height) { Preconditions.checkState(mSurfaceTexture == surfaceTexture); Log.d(TAG, "onSurfaceTextureSizeChanged(width:" + width + ", height: " + height + " )"); } @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture surfaceTexture) { if (mSurfaceCompleter == null && mSurfaceReleaseFuture != null) { mSurfaceReleaseFuture.addListener(surfaceTexture::release, ContextCompat.getMainExecutor(mTextureView.getContext())); return false; } else { return true; } } @Override public void onSurfaceTextureUpdated(final SurfaceTexture surfaceTexture) { } }); parent.addView(mTextureView); }

Target:
public void init(@NonNull FrameLayout parent) { mTextureView = new TextureView(parent.getContext()); mTextureView.setLayoutParams( new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(final SurfaceTexture surfaceTexture, final int width, final int height) { mSurfaceTexture = surfaceTexture; tryToProvidePreviewSurface(); } @Override public void onSurfaceTextureSizeChanged(final SurfaceTexture surfaceTexture, final int width, final int height) { Log.d(TAG, "onSurfaceTextureSizeChanged(width:" + width + ", height: " + height + " )"); } @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture surfaceTexture) { mSurfaceTexture = null; if (mSurfaceCompleter == null && mSurfaceReleaseFuture != null) { mSurfaceReleaseFuture.addListener(surfaceTexture::release, ContextCompat.getMainExecutor(mTextureView.getContext())); return false; } else { return true; } } @Override public void onSurfaceTextureUpdated(final SurfaceTexture surfaceTexture) { } }); parent.addView(mTextureView); }
Source:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); int end = buf.limit(); while (buf.remaining() > ATTR_HEADER_LEN) { short attrLen = buf.getShort(); short attrId = nested(buf.getShort()); buf.limit(end); handler.use(buf, attrId); buf.position(start); } }

Target:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); if (buf.remaining() > ATTR_HEADER_LEN) { short attrLen = buf.getShort(); short attrId = nested(buf.getShort()); handler.use(buf, attrId); buf.position(start); } }
Source:
public void CompleteUDPPacketTest() throws IOException, BadPcapFileException, BadPacketException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); PcapFile dummy = trace.getTrace(); ByteBuffer byteBuffer = fPacket; if (byteBuffer == null) { fail("CompleteUDPPacketTest has failed!"); return; } UDPPacket packet = new UDPPacket(dummy, null, byteBuffer); assertEquals(PcapProtocol.UDP, packet.getProtocol()); assertTrue(packet.hasProtocol(PcapProtocol.UDP)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.ETHERNET_II)); assertTrue(packet.validate()); assertEquals(473000225, packet.hashCode()); assertFalse(packet.equals(null)); assertEquals(new UDPPacket(dummy, null, byteBuffer), packet); assertEquals(EXPECTED_FIELDS, packet.getFields()); assertEquals(EXPTECTED_TOSTRING, packet.toString()); assertEquals("Src Port: 18057, Dst Port: 39611", packet.getLocalSummaryString()); assertEquals("Source Port: 18057, Destination Port: 39611", packet.getGlobalSummaryString()); assertEquals(new UDPEndpoint(packet, true), packet.getSourceEndpoint()); assertEquals(new UDPEndpoint(packet, false), packet.getDestinationEndpoint()); fPacket.position(8); byte[] payload = new byte[4]; fPacket.get(payload); assertEquals(ByteBuffer.wrap(payload), packet.getPayload()); assertEquals(0x4689, packet.getSourcePort()); assertEquals(0x9ABB, packet.getDestinationPort()); assertEquals(0xA1EC, packet.getTotalLength()); assertEquals(0xFAAF, packet.getChecksum()); }

Target:
public void CompleteUDPPacketTest() throws IOException, BadPcapFileException, BadPacketException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { ByteBuffer byteBuffer = fPacket; if (byteBuffer == null) { fail("CompleteUDPPacketTest has failed!"); return; } UDPPacket packet = new UDPPacket(dummy, null, byteBuffer); assertEquals(PcapProtocol.UDP, packet.getProtocol()); assertTrue(packet.hasProtocol(PcapProtocol.UDP)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.ETHERNET_II)); assertTrue(packet.validate()); assertEquals(473000225, packet.hashCode()); assertFalse(packet.equals(null)); assertEquals(new UDPPacket(dummy, null, byteBuffer), packet); assertEquals(EXPECTED_FIELDS, packet.getFields()); assertEquals(EXPTECTED_TOSTRING, packet.toString()); assertEquals("Src Port: 18057, Dst Port: 39611", packet.getLocalSummaryString()); assertEquals("Source Port: 18057, Destination Port: 39611", packet.getGlobalSummaryString()); assertEquals(new UDPEndpoint(packet, true), packet.getSourceEndpoint()); assertEquals(new UDPEndpoint(packet, false), packet.getDestinationEndpoint()); fPacket.position(8); byte[] payload = new byte[4]; fPacket.get(payload); assertEquals(ByteBuffer.wrap(payload), packet.getPayload()); assertEquals(0x4689, packet.getSourcePort()); assertEquals(0x9ABB, packet.getDestinationPort()); assertEquals(0xA1EC, packet.getTotalLength()); assertEquals(0xFAAF, packet.getChecksum()); } }
Source:
public void removingEntriesRetentionsEventsInLog() { eventCache.processStartTransactionsUpdate(TIMESTAMPS, SNAPSHOT); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS); verifyStage(); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); }

Target:
public void removingEntriesRetentionsEventsInLog() { setupInitialState(); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS); verifyStage(); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); }
Source:
CorfuStreamEntry fromSMREntry(@Nonnull SMREntry entry, final long epoch) { long address = entry.getGlobalAddress(); OperationType operationType; switch(entry.getSMRMethod()) { case "put": case "putAll": operationType = OperationType.UPDATE; break; case "clear": operationType = OperationType.CLEAR; break; case "remove": operationType = OperationType.DELETE; break; default: throw new RuntimeException("SMRMethod "+entry.getSMRMethod() + " cannot be translated to CorfuStreamEntry"); } Object[] args = entry.getSMRArguments(); if (args.length > 0) { if (args.length > 1) { CorfuRecord record = (CorfuRecord) args[1]; return new CorfuStreamEntry((Message)args[0], record.getPayload(), record.getMetadata(), 0, address, operationType); } } return new CorfuStreamEntry((Message)args[0], null, null, 0, address, operationType); }

Target:
CorfuStreamEntry fromSMREntry(@Nonnull SMREntry entry, final long epoch) { long address = entry.getGlobalAddress(); OperationType operationType = getOperationType(entry); Object[] args = entry.getSMRArguments(); if (args.length > 0) { if (args.length > 1) { CorfuRecord record = (CorfuRecord) args[1]; return new CorfuStreamEntry((Message)args[0], record.getPayload(), record.getMetadata(), 0, address, operationType); } return new CorfuStreamEntry((Message)args[0], null, null, 0, address, operationType); } return new CorfuStreamEntry(null, null, null, 0, address, operationType); }
Source:
public String toString() { return String.format("%s[%d, %d]", this.getClass().getSimpleName(), min(), max()); }

Target:
public String toString() { return String.format("%s[%s:%d, %s:%d]", this.getClass().getSimpleName(), this.minKeyLabel, min(), this.maxKeyLabel, max()); }
Source:
public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Submitting Task to Context: {0}", activeContext); final String taskId = activeContext.getId(); final Configuration nameResolverConf = NameResolverConfiguration.CONF .set(NameResolverConfiguration.NAME_SERVICE_PORT, nameServer.getPort()) .set(NameResolverConfiguration.NAME_SERVER_HOSTNAME, localAddressProvider.getLocalAddress()) .build(); final Configuration taskConfiguration = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, taskId) .set(TaskConfiguration.TASK, MistTask.class) .build(); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(NumExecutors.class, numTaskCores+""); activeContext.submitTask( Configurations.merge(nameResolverConf, taskConfiguration, jcb.build())); }

Target:
public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Submitting Task to Context: {0}", activeContext); final String taskId = activeContext.getId(); final Configuration nameResolverConf = NameResolverConfiguration.CONF .set(NameResolverConfiguration.NAME_SERVICE_PORT, nameServer.getPort()) .set(NameResolverConfiguration.NAME_SERVER_HOSTNAME, localAddressProvider.getLocalAddress()) .build(); final Configuration taskConfiguration = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, taskId) .set(TaskConfiguration.TASK, MistTask.class) .build(); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(NumExecutors.class, mistTaskConfigs.getNumTaskExecutors()+""); activeContext.submitTask( Configurations.merge(nameResolverConf, taskConfiguration, jcb.build())); }
Source:
public static void afterAll() throws Exception { if (Strings.isNullOrEmpty(PROJECT_ID)) { return; } try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(PROJECT_ID, SECRET_ID); DeleteSecretRequest deleteRequest = DeleteSecretRequest.newBuilder().setName(name.toString()).build(); client.deleteSecret(deleteRequest); } }

Target:
public static void afterAll() throws Exception { Assert.assertFalse("missing GOOGLE_CLOUD_PROJECT", Strings.isNullOrEmpty(PROJECT_ID)); try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(PROJECT_ID, SECRET_ID); DeleteSecretRequest deleteRequest = DeleteSecretRequest.newBuilder().setName(name.toString()).build(); client.deleteSecret(deleteRequest); } }
Source:
private boolean getBoolean(String param) throws ServletException { String n = getInitParameter(param); if (n == null) return false; else if (StringUtils.equalsIgnoreCase("yes", n) || StringUtils.equalsIgnoreCase("true", n) || StringUtils.equalsIgnoreCase("1", n) || StringUtils.equalsIgnoreCase("on", n)) return true; else if (StringUtils.equalsIgnoreCase("no", n) || StringUtils.equalsIgnoreCase("false", n) || StringUtils.equalsIgnoreCase("0", n) || StringUtils.equalsIgnoreCase("off", n)) return false; else throw new ServletException("Invalid boolean " + param + " = " + n); }

Target:
private boolean getBoolean(String param) throws ServletException { String n = getInitParameter(param); if (n == null) return false; try { return StringUtils.toBoolean(n); } catch (IllegalArgumentException err) { throw new ServletException("Invalid boolean " + param + " = " + n); } }
Source:
public CalculationResult execute(ScenarioMarketData marketData) { Result<?> result; try { DefaultCalculationMarketData calculationData = new DefaultCalculationMarketData(marketData, marketDataMappings); result = Result.success(function.execute(target, calculationData, reportingRules)); } catch (Exception e) { result = Result.failure(e); } return CalculationResult.of(target, rowIndex, columnIndex, result); }

Target:
public CalculationResult execute(ScenarioMarketData marketData) { DefaultCalculationMarketData calculationData = new DefaultCalculationMarketData(marketData, marketDataMappings); Result<?> result = Result.of(() -> function.execute(target, calculationData, reportingRules)); return CalculationResult.of(target, rowIndex, columnIndex, result); }
Source:
public <T> T getService(long consumerID, ServiceConfiguration<T> unknownConfiguration) { if (unknownConfiguration instanceof OffHeapResourceIdentifier) { OffHeapResourceIdentifier identifier = (OffHeapResourceIdentifier) unknownConfiguration; return (T) identifier.getServiceType().cast(resources.get(identifier)); } else if (OffHeapResources.class.isAssignableFrom(unknownConfiguration.getServiceType())) { return (T) new OffHeapResources() { @Override public Set<OffHeapResourceIdentifier> getAllIdentifiers() { return resources.keySet(); } }; } else { throw new IllegalArgumentException("Unexpected configuration type " + unknownConfiguration.getClass()); } }

Target:
public <T> T getService(long consumerID, ServiceConfiguration<T> unknownConfiguration) { if (unknownConfiguration instanceof OffHeapResourceIdentifier) { OffHeapResourceIdentifier identifier = (OffHeapResourceIdentifier) unknownConfiguration; return (T) identifier.getServiceType().cast(resources.get(identifier)); } else if (OffHeapResources.class.isAssignableFrom(unknownConfiguration.getServiceType())) { return (T) new OffHeapResources() { @Override public Set<String> getAllIdentifiers() { Set<String> names = new HashSet<String>(); for (OffHeapResourceIdentifier identifier: resources.keySet()) { names.add(identifier.getName()); } return Collections.unmodifiableSet(names); } }; } else { throw new IllegalArgumentException("Unexpected configuration type " + unknownConfiguration.getClass()); } }
Source:
public void performSearchOnNonEmptyQuery(Set<SearchBasedFetcher> fetchers) { CompositeSearchBasedFetcher compositeFetcher = new CompositeSearchBasedFetcher(fetchers); List<BibEntry> compositeResult = compositeFetcher.performSearch("quantum"); for (SearchBasedFetcher fetcher : fetchers) { try { Assertions.assertTrue(compositeResult.containsAll(fetcher.performSearch("quantum"))); } catch (FetcherException e) { LOGGER.warn(String.format("Fetcher %s failed ", fetcher.getName()), e); } } }

Target:
public void performSearchOnNonEmptyQuery(Set<SearchBasedFetcher> fetchers) { CompositeSearchBasedFetcher compositeFetcher = new CompositeSearchBasedFetcher(fetchers, Integer.MAX_VALUE); List<BibEntry> compositeResult = compositeFetcher.performSearch("quantum"); for (SearchBasedFetcher fetcher : fetchers) { try { Assertions.assertTrue(compositeResult.containsAll(fetcher.performSearch("quantum"))); } catch (FetcherException e) { LOGGER.debug(String.format("Fetcher %s failed ", fetcher.getName()), e); } } }
Source:
private void rebuildIndexes(Connection conn, Configuration conf, ArrayList<String> tableList) { if (!upgrade) { return; } if (!rebuild) { return; } for (String table: tableList) { rebuildIndexes(conn, conf, table); } }

Target:
private void rebuildIndexes(Connection conn, Configuration conf, ArrayList<String> tableList) { if (!upgrade || !rebuild) { return; } for (String table: tableList) { rebuildIndexes(conn, conf, table); } }
Source:
public String updateQuantity(HttpServletRequest request, HttpServletResponse response, Model model, OrderItemRequestDTO itemRequest) throws IOException, UpdateCartException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.updateItemQuantity(cart.getId(), itemRequest, true); cart = orderService.save(cart, false); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<>(); extraData.put("productId", itemRequest.getProductId()); extraData.put("cartItemCount", cart.getItemCount()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } }

Target:
public String updateQuantity(HttpServletRequest request, HttpServletResponse response, Model model, OrderItemRequestDTO itemRequest) throws IOException, UpdateCartException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.updateItemQuantity(cart.getId(), itemRequest, true); cart = orderService.save(cart, false); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<>(); extraData.put("skuId", itemRequest.getSkuId()); extraData.put("productId", itemRequest.getProductId()); extraData.put("cartItemCount", cart.getItemCount()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } }
Source:
public void createIndexOverOneField() { String indexName = im.ensureIndexed(Arrays.<Object>asList("name"), "basic"); assertThat(indexName, is(notNullValue())); assertThat(indexName, is("basic")); Map<String, Object> indexes = im.listIndexes(); assertThat(indexes, hasKey("basic")); @SuppressWarnings("unchecked") Map<String, Object> index = (Map<String, Object>) indexes.get("basic"); @SuppressWarnings("unchecked") List<String> fields = (List<String>) index.get("fields"); assertThat(fields, containsInAnyOrder("_id", "_rev", "name")); }

Target:
public void createIndexOverOneField() { String indexName = im.ensureIndexed(Arrays.<Object>asList("name"), "basic"); assertThat(indexName, is("basic")); Map<String, Object> indexes = im.listIndexes(); assertThat(indexes, hasKey("basic")); @SuppressWarnings("unchecked") Map<String, Object> index = (Map<String, Object>) indexes.get("basic"); @SuppressWarnings("unchecked") List<String> fields = (List<String>) index.get("fields"); assertThat(fields, containsInAnyOrder("_id", "_rev", "name")); }
Source:
public void deleteCourseGroup(CourseGroup course) { try { solrServer.deleteById(new Integer(course.getMuid()).toString()); } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void deleteCourseGroup(CourseGroup course) { try { solrServer.deleteById(new Integer(course.getMuid()).toString()); } catch (SolrServerException e) { log.error(e.getLocalizedMessage() + " whilst processing course [" + course.getCourseId() + ":" + course.getTitle() +"]", e); } catch (IOException e) { log.error(e.getLocalizedMessage() + " whilst processing course [" + course.getCourseId() + ":" + course.getTitle() +"]", e); } }
Source:
public void service(org.zkoss.zk.au.AuRequest request, boolean everError) { final String cmd = request.getCommand(); if (cmd.equals(Events.ON_CHECK)) { CheckEvent evt = CheckEvent.getCheckEvent(request); if ("tristate".equals(getMold())) { Boolean state = evt.getState(); if (state == null) { _indeterminate = true; _checked = false; } else if (state) { _indeterminate = false; _checked = true; } else { _indeterminate = false; _checked = false; } } else { _checked = evt.isChecked(); _indeterminate = false; } Events.postEvent(evt); } else super.service(request, everError); }

Target:
public void service(org.zkoss.zk.au.AuRequest request, boolean everError) { final String cmd = request.getCommand(); if (cmd.equals(Events.ON_CHECK)) { CheckEvent evt = CheckEvent.getCheckEvent(request); if ("tristate".equals(getMold())) { Boolean state = evt.getState(); _checked = (state != null) && state; _indeterminate = state == null; } else { _checked = evt.isChecked(); _indeterminate = false; } Events.postEvent(evt); } else super.service(request, everError); }
Source:
public static HashMap<String, String> createJMSListeningParameterMap(String destinationName, String connectionFactory, String destinationType, String jmsMode) { HashMap<String, String> jmsDestinationListeningParameters = new HashMap<>(); jmsDestinationListeningParameters.put(JMSConstants.DESTINATION_PARAM_NAME, destinationName); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_JNDI_PARAM_NAME, connectionFactory); jmsDestinationListeningParameters .put(JMSConstants.NAMING_FACTORY_INITIAL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_FACTORY_INITIAL); jmsDestinationListeningParameters.put(JMSConstants.PROVIDER_URL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_PROVIDER_URL); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_TYPE_PARAM_NAME, destinationType); jmsDestinationListeningParameters.put(JMSConstants.SESSION_ACK_MODE_PARAM_NAME, jmsMode); return jmsDestinationListeningParameters; }

Target:
public static Map<String, String> createJMSListeningParameterMap(String destinationName, String connectionFactory, String destinationType, String jmsMode) { HashMap<String, String> jmsDestinationListeningParameters = new HashMap<>(); jmsDestinationListeningParameters.put(JMSConstants.DESTINATION_PARAM_NAME, destinationName); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_JNDI_PARAM_NAME, connectionFactory); jmsDestinationListeningParameters .put(JMSConstants.NAMING_FACTORY_INITIAL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_FACTORY_INITIAL); jmsDestinationListeningParameters.put(JMSConstants.PROVIDER_URL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_PROVIDER_URL); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_TYPE_PARAM_NAME, destinationType); jmsDestinationListeningParameters.put(JMSConstants.SESSION_ACK_MODE_PARAM_NAME, jmsMode); return jmsDestinationListeningParameters; }
Source:
public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || this.self == friend.alias()) { continue; } this.email(friend, text); } }

Target:
public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || this.self.equals(friend.alias())) { continue; } this.email(friend, text); } }
Source:
protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table("); context.out.write("type=ts,threshold=" + tsWindowThreshold); context.out.write(",columns="); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write(":"); } } context.out.write(")\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); if (materializedTable.size() != 0) { long maxTimestamp = ((java.sql.Timestamp) materializedTable.get(materializedTable.size() - 1) .getField(0)).getTime(); materializedTable = materializedTable.stream() .filter(row -> ((java.sql.Timestamp) row.getField(0)).getTime() > maxTimestamp - tsWindowThreshold) .collect(Collectors.toList()); LOGGER.debug("*****************Row size: " + materializedTable.size()); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } LOGGER.debug("Row:" + row); context.out.write("\n"); } } context.out.flush(); } catch (IOException e) { e.printStackTrace(); LOGGER.error("Fail to refresh data", e); } }

Target:
protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); if (materializedTable.size() != 0) { long maxTimestamp = ((java.sql.Timestamp) materializedTable.get(materializedTable.size() - 1) .getField(0)).getTime(); materializedTable = materializedTable.stream() .filter(row -> ((java.sql.Timestamp) row.getField(0)).getTime() > maxTimestamp - tsWindowThreshold) .collect(Collectors.toList()); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } context.out.write("\n"); } } context.out.flush(); } catch (IOException e) { LOGGER.error("Fail to refresh data", e); } }
Source:
public void write(final InputStream input, final long size) throws IOException { if (size == 0) { throw new IllegalArgumentException( "the document size should be greater 0" ); } final Ocket ocket = this.ocket(); if (ocket.exists() && ocket.meta().getUserMetaDataOf(AwsDoc.HEADER) != null) { throw new IllegalStateException("you can't write to this doc"); } final ObjectMetadata meta = new ObjectMetadata(); if (size > 0) { meta.setContentLength(size); } ocket.write(input, meta); Logger.info(this, "%d bytes saved to %s", size, ocket.key()); }

Target:
public void write(final InputStream input, final long size) throws IOException { final Ocket ocket = this.ocket(); if (ocket.exists() && ocket.meta().getUserMetaDataOf(AwsDoc.HEADER) != null) { throw new IllegalStateException("you can't write to this doc"); } final ObjectMetadata meta = new ObjectMetadata(); if (size > 0) { meta.setContentLength(size); } ocket.write(input, meta); Logger.info(this, "%d bytes saved to %s", size, ocket.key()); }
Source:
SubresourceParameter(String value) { super("t", value); }

Target:
public SubresourceParameter(String value) { super("t", value); }
Source:
private static boolean isRepoQualifier(Qualifier q) { switch (q.getType()) { case REPO: return true; default: return false; } }

Target:
private static boolean isRepoQualifier(Qualifier q) { return q.getType() == QualifierType.REPO; }
Source:
public boolean isDirty() { return StreamSupport.stream( instanceSelector.flatMap( IndexAccessor::isDirty ).spliterator(), false ) .anyMatch( Boolean::booleanValue ); }

Target:
public boolean isDirty() { return Iterables.stream( instanceSelector.transform( IndexAccessor::isDirty ) ).anyMatch( Boolean::booleanValue ); }
Source:
public static int intUnnecessaryShiftMasking(int value, int shift) { return value << (shift & 31); }

Target:
public static int $noinline$intUnnecessaryShiftMasking(int value, int shift) { if (doThrow) { throw new Error(); } return value << (shift & 31); }
Source:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); return (doubleValue == null ? new Double(0.0) : doubleValue); }

Target:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); return (doubleValue == null ? Double.valueOf(0.0) : doubleValue); }
Source:
public List<ToolLocationNodeProperty> getNodeProperties(){ return nodeProperties; }

Target:
public List<ToolLocationNodeProperty> getNodeProperties(){ if (nodeProperties == null) { return Collections.emptyList(); } return nodeProperties; }