auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void showQuickStartDialog() { if (AppPrefs.isQuickStartDisabled() || getSelectedSite() == null || !QuickStartUtils.isQuickStartAvailableForTheSite(getSelectedSite())) { return; } String tag = MySiteFragment.TAG_QUICK_START_DIALOG; PromoDialog promoDialog = new PromoDialog(); promoDialog.initialize( tag, getString(R.string.quick_start_dialog_need_help_title), getString(R.string.quick_start_dialog_need_help_message), getString(R.string.quick_start_dialog_need_help_button_positive), R.drawable.img_promo_quick_start, getString(R.string.quick_start_dialog_need_help_button_negative), "", getString(R.string.quick_start_dialog_need_help_button_neutral) ); promoDialog.show(getSupportFragmentManager(), tag); <START> AnalyticsTracker.track(AnalyticsTracker.Stat.QUICK_START_REQUEST_SEEN); <END> }</code><technical_language>remove unnecessary AnalyticsTracker qualification AnalyticsTracker.Stat.QUICK_START_REQUEST_SEEN produce AnalyticsTracker.track(Stat.QUICK_START_REQUEST_SEEN); for simplicity</technical_language>

Target:
private void showQuickStartDialog() { if (AppPrefs.isQuickStartDisabled() || getSelectedSite() == null || !QuickStartUtils.isQuickStartAvailableForTheSite(getSelectedSite())) { return; } String tag = MySiteFragment.TAG_QUICK_START_DIALOG; PromoDialog promoDialog = new PromoDialog(); promoDialog.initialize( tag, getString(R.string.quick_start_dialog_need_help_title), getString(R.string.quick_start_dialog_need_help_message), getString(R.string.quick_start_dialog_need_help_button_positive), R.drawable.img_promo_quick_start, getString(R.string.quick_start_dialog_need_help_button_negative), "", getString(R.string.quick_start_dialog_need_help_button_neutral) ); promoDialog.show(getSupportFragmentManager(), tag); AnalyticsTracker.track(Stat.QUICK_START_REQUEST_VIEWED); }
Source:
<code>public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { if (clientId != null && this.clientId.toLowerCase().contains(clientId.toLowerCase())) { return Collections.singletonList(new ClientAdapter(realm)); } <START> return null; <END> }</code><technical_language>return new ArrayList<ClientModel>(); Collections.EMPTY_LIST</technical_language>

Target:
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { if (clientId != null && this.clientId.toLowerCase().contains(clientId.toLowerCase())) { return Collections.singletonList(new ClientAdapter(realm)); } return Collections.EMPTY_LIST; }
Source:
<code>public List<Event> getEventsSinceId(String workflowId, int eventId, int maxEvents) throws IOException { <START> Preconditions.checkArgument(maxEvents > 0); <END> WorkflowId id = WorkflowId.parseString(workflowId); FlowEventKey flowEventKey = new FlowEventKey(toFlowKey(id), eventId); List<FlowEvent> flowEventList = flowEventService.getFlowEventsSince(flowEventKey); int numElems = 0; List<Event> workflowEvents = Lists.newArrayList(); for (FlowEvent flowEvent : flowEventList) { if (numElems >= maxEvents) { break; } String eventDataJson = flowEvent.getEventDataJSON(); try { Event event = Event.fromJson(eventDataJson); numElems++; workflowEvents.add(event); } catch (JsonMappingException e) { LOG.error("Could not deserialize json: " + eventDataJson, e); } } return workflowEvents; }</code><technical_language>other preconditions other args</technical_language>

Target:
public List<Event> getEventsSinceId(String workflowId, int eventId, int maxEvents) throws IOException { Preconditions.checkArgument(maxEvents > 0); WorkflowId id = WorkflowId.parseString(workflowId); FlowEventKey flowEventKey = new FlowEventKey(toFlowKey(id), eventId); List<FlowEvent> flowEventList = flowEventService.getFlowEventsSince(flowEventKey); int numElems = 0; List<Event> workflowEvents = Lists.newArrayListWithCapacity(maxEvents); for (FlowEvent flowEvent : flowEventList) { if (numElems >= maxEvents) { break; } String eventDataJson = flowEvent.getEventDataJSON(); try { Event event = Event.fromJson(eventDataJson); numElems++; workflowEvents.add(event); } catch (JsonMappingException e) { LOG.error("Could not deserialize json: " + eventDataJson, e); } } return workflowEvents; }
Source:
<code>private static PolymorphicScalarFunctionBuilder castFunctionToDecimalFromBuilder(TypeSignature from, boolean nullableResult, String... methodNames) { Signature signature = Signature.builder() .kind(SCALAR) .operatorType(CAST) .argumentTypes(from) .returnType(parseTypeSignature("decimal(precision,scale)", ImmutableSet.of("precision", "scale"))) .build(); return SqlScalarFunction.builder(DecimalCasts.class) .signature(signature) .deterministic(true) <START> .choice(c -> c <END> .nullableResult(nullableResult) .implementation(b -> b .methods(methodNames) .withExtraParameters((context) -> { DecimalType resultType = (DecimalType) context.getReturnType(); Number tenToScale; if (isShortDecimal(resultType)) { tenToScale = longTenToNth(resultType.getScale()); } else { tenToScale = bigIntegerTenToNth(resultType.getScale()); } return ImmutableList.of(resultType.getPrecision(), resultType.getScale(), tenToScale); }))); }</code><technical_language>nit: choice -> choice</technical_language>

Target:
private static SqlScalarFunction castFunctionToDecimalFromBuilder(TypeSignature from, boolean nullableResult, String... methodNames) { Signature signature = Signature.builder() .kind(SCALAR) .operatorType(CAST) .argumentTypes(from) .returnType(parseTypeSignature("decimal(precision,scale)", ImmutableSet.of("precision", "scale"))) .build(); return SqlScalarFunction.builder(DecimalCasts.class) .signature(signature) .deterministic(true) .choice(choice -> choice .nullableResult(nullableResult) .implementation(methodsGroup -> methodsGroup .methods(methodNames) .withExtraParameters((context) -> { DecimalType resultType = (DecimalType) context.getReturnType(); Number tenToScale; if (isShortDecimal(resultType)) { tenToScale = longTenToNth(resultType.getScale()); } else { tenToScale = bigIntegerTenToNth(resultType.getScale()); } return ImmutableList.of(resultType.getPrecision(), resultType.getScale(), tenToScale); }))).build(); }
Source:
<code>public void setupMocks() { <START> MockitoAnnotations.initMocks(this); <END> constraintViolationBuilder = mock(ConstraintValidatorContext.ConstraintViolationBuilder.class); nodeBuilderCustomizableContext = mock(ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext.class); validatorContext = mock(ConstraintValidatorContext.class); when(validatorContext.buildConstraintViolationWithTemplate(any())).thenReturn(constraintViolationBuilder); when(constraintViolationBuilder.addPropertyNode(any())).thenReturn(nodeBuilderCustomizableContext); when(nodeBuilderCustomizableContext.addConstraintViolation()).thenReturn(validatorContext); doNothing().when(validatorContext).disableDefaultConstraintViolation(); }</code><technical_language>this work this class is annotated @RunWith(MockitoJUnitRunner.class) I missing something</technical_language>

Target:
public void setupMocks() { constraintViolationBuilder = mock(ConstraintValidatorContext.ConstraintViolationBuilder.class); nodeBuilderCustomizableContext = mock(ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext.class); validatorContext = mock(ConstraintValidatorContext.class); when(validatorContext.buildConstraintViolationWithTemplate(any())).thenReturn(constraintViolationBuilder); when(constraintViolationBuilder.addPropertyNode(any())).thenReturn(nodeBuilderCustomizableContext); when(nodeBuilderCustomizableContext.addConstraintViolation()).thenReturn(validatorContext); doNothing().when(validatorContext).disableDefaultConstraintViolation(); }
Source:
<code>protected void assertEquals(IPath parent, RemoteFolder container1, RemoteFolder container2, boolean includeTags) throws CoreException, TeamException, IOException { IPath path = parent.append(container1.getName()); assertEquals(path, container1.getFolderSyncInfo(), container2.getFolderSyncInfo(), includeTags); ICVSRemoteResource[] members1 = container1.getMembers(DEFAULT_MONITOR); ICVSRemoteResource[] members2 = container2.getMembers(DEFAULT_MONITOR); assertTrue("Number of members differ for " + path, members1.length == members2.length); Map<String, ICVSRemoteResource> memberMap2 = new HashMap<>(); for (ICVSRemoteResource <START> members21 : <END> members2) { memberMap2.put(members21.getName(), members21); } for (ICVSRemoteResource members11 : members1) { ICVSRemoteResource member2 = memberMap2.get(members11.getName()); assertNotNull("Resource does not exist: " + path.append(members11.getName()) + member2); assertEquals(path, members11, member2, includeTags); } }</code><technical_language>find name</technical_language>

Target:
protected void assertEquals(IPath parent, RemoteFolder container1, RemoteFolder container2, boolean includeTags) throws CoreException, TeamException, IOException { IPath path = parent.append(container1.getName()); assertEquals(path, container1.getFolderSyncInfo(), container2.getFolderSyncInfo(), includeTags); ICVSRemoteResource[] members1 = container1.getMembers(DEFAULT_MONITOR); ICVSRemoteResource[] members2 = container2.getMembers(DEFAULT_MONITOR); assertTrue("Number of members differ for " + path, members1.length == members2.length); Map<String, ICVSRemoteResource> memberMap2 = new HashMap<>(); for (ICVSRemoteResource m : members2) { memberMap2.put(m.getName(), m); } for (ICVSRemoteResource _m : members1) { ICVSRemoteResource member2 = memberMap2.get(_m.getName()); assertNotNull("Resource does not exist: " + path.append(_m.getName()) + member2); assertEquals(path, _m, member2, includeTags); } }
Source:
<code>public ByteAmount multiply(int factor) { Preconditions.checkArgument(asBytes() <= Long.MAX_VALUE / factor, String.format( <START> "Subtracting %s from %s would overshoot Long.MIN_LONG", this, factor)); <END> return ByteAmount.fromBytes(asBytes() * factor); }</code><technical_language>fix error message</technical_language>

Target:
public ByteAmount multiply(int factor) { Preconditions.checkArgument(asBytes() <= Long.MAX_VALUE / factor, String.format( "Multiplying %s by %d would exceed Long.MAX_LONG", this, factor)); return ByteAmount.fromBytes(asBytes() * factor); }
Source:
<code>public Iterable<ValidationResult> doHealthChecks(RuntimeContainer container) { AzureDlsGen2BlobSource source = new AzureDlsGen2BlobSource(); AzureDlsGen2BlobInputProperties properties = new AzureDlsGen2BlobInputProperties("health"); AzureDlsGen2BlobDatasetProperties dataset = new AzureDlsGen2BlobDatasetProperties("dataprep"); dataset.setDatastoreProperties(datastore); properties.setDatasetProperties(dataset); source.initialize(container, properties); <START> return Arrays.asList(source.validate(container)); <END> }</code><technical_language>Arrays.singleton()</technical_language>

Target:
public Iterable<ValidationResult> doHealthChecks(RuntimeContainer container) { AzureDlsGen2BlobSource source = new AzureDlsGen2BlobSource(); AzureDlsGen2BlobInputProperties properties = new AzureDlsGen2BlobInputProperties("health"); AzureDlsGen2BlobDatasetProperties dataset = new AzureDlsGen2BlobDatasetProperties("dataprep"); dataset.setDatastoreProperties(datastore); properties.setDatasetProperties(dataset); source.initialize(container, properties); return Collections.singletonList(source.validate(container)); }
Source:
<code><START> void extendTicket() { <END> assertDoesNotThrow(() -> imageioClient.extendTicket(imageTicket.getId(), 300)); }</code><technical_language>putTicket(...) Need check ticket exists expires increased timeout: putTicket(...) current = getTiket().getExpires() extendTicket(..) new = getTicket().getExpires() assert new == current + timeout</technical_language>

Target:
void extendTicket() { imageioClient.putTicket(imageTicket); ImageTicketInformation oldTicket = imageioClient.getTicket(imageTicket.getId()); assertDoesNotThrow(() -> imageioClient.extendTicket(imageTicket.getId(), 600)); ImageTicketInformation newTicket = imageioClient.getTicket(imageTicket.getId()); assertTrue(newTicket.getExpires() >= oldTicket.getExpires() + oldTicket.getTimeout()); assertTrue(oldTicket.getExpires() + oldTicket.getTimeout() + 1 >= newTicket.getExpires()); }
Source:
<code>private boolean isYoungerThanThisNode(PathChildrenCacheEvent event) { Stat stat = event.getData().getStat(); <START> return stat.getCtime() > initializationTime && stat.getMtime() > initializationTime; <END> }</code><technical_language>hey, this work actually. need check mtime operator here. If reaper delete node another retransmission is issued, applied</technical_language>

Target:
private boolean isYoungerThanThisNode(PathChildrenCacheEvent event) { return event.getData().getStat().getMtime() > initializationTime; }
Source:
<code>public double max(String colName) { <START> double[] colArray = toDoubleArray(colName); double arrayMax = StatUtils.max(colArray); return arrayMax; <END> }</code><technical_language>return StatUtils. max(toDoubleArray(colName)) directly</technical_language>

Target:
public double max(String colName) { return StatUtils.max(toDoubleArray(colName)); }
Source:
<code>public boolean isKeepNext() { <START> if (getCTP() != null && getCTP().getPPr() != null) { <END> return getCTP().getPPr().setKeepNext(on); } }</code><technical_language>this compile? me, this return if if-condition fails</technical_language>

Target:
public boolean isKeepNext() { if (getCTP() != null && getCTP().getPPr() != null && getCTP().getPPr().isSetKeepNext()) { return getCTP().getPPr().getKeepNext().getVal() == STOnOff.ON; } return false; }
Source:
<code>protected StandardIntegrationFlow get() { if (this.integrationFlow == null) { if (this.currentMessageChannel instanceof FixedSubscriberChannelPrototype) { throw new BeanCreationException("The 'currentMessageChannel' (" + this.currentMessageChannel + ") is a prototype for 'FixedSubscriberChannel' which can't be created without " + <START> "'MessageHandler' " <END> + "constructor argument. That means that '.fixedSubscriberChannel()' can't be the last " + "EIP-method in the 'IntegrationFlow' definition."); } if (this.integrationComponents.size() == 1) { if (this.currentComponent != null) { if (this.currentComponent instanceof SourcePollingChannelAdapterSpec) { throw new BeanCreationException("The 'SourcePollingChannelAdapter' (" + this.currentComponent + ") " + "must be configured with at least one 'MessageChannel' or 'MessageHandler'."); } } else if (this.currentMessageChannel != null) { throw new BeanCreationException("The 'IntegrationFlow' can't consist of only one 'MessageChannel'. " + "Add at lest '.bridge()' EIP-method before the end of flow."); } } if (this.implicitChannel) { Optional<Object> lastComponent = this.integrationComponents.keySet() .stream() .reduce((first, second) -> second); if (lastComponent.get() instanceof WireTapSpec) { channel(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); } } this.integrationFlow = new StandardIntegrationFlow(this.integrationComponents); } return this.integrationFlow; }</code><technical_language>**a** 'MessageHandler'</technical_language>

Target:
protected StandardIntegrationFlow get() { if (this.integrationFlow == null) { if (this.currentMessageChannel instanceof FixedSubscriberChannelPrototype) { throw new BeanCreationException("The 'currentMessageChannel' (" + this.currentMessageChannel + ") is a prototype for 'FixedSubscriberChannel' which can't be created without " + "a 'MessageHandler' constructor argument. " + "That means that '.fixedSubscriberChannel()' can't be the last " + "EIP-method in the 'IntegrationFlow' definition."); } if (this.integrationComponents.size() == 1) { if (this.currentComponent != null) { if (this.currentComponent instanceof SourcePollingChannelAdapterSpec) { throw new BeanCreationException("The 'SourcePollingChannelAdapter' (" + this.currentComponent + ") " + "must be configured with at least one 'MessageChannel' or 'MessageHandler'."); } } else if (this.currentMessageChannel != null) { throw new BeanCreationException("The 'IntegrationFlow' can't consist of only one 'MessageChannel'. " + "Add at lest '.bridge()' EIP-method before the end of flow."); } } if (this.implicitChannel) { Optional<Object> lastComponent = this.integrationComponents.keySet() .stream() .reduce((first, second) -> second); if (lastComponent.get() instanceof WireTapSpec) { channel(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); } } this.integrationFlow = new StandardIntegrationFlow(this.integrationComponents); } return this.integrationFlow; }
Source:
<code>public Object visit(PropertyIsLike filter, Object extraData) { BasicDBObject output = asDBObject(extraData); <START> String expr = convert(filter.getExpression().accept(this, null), String.class); <END> String multi = filter.getWildCard(); String single = filter.getSingleChar(); int flags = (filter.isMatchingCase()) ? 0 : Pattern.CASE_INSENSITIVE; String regex = filter.getLiteral().replace(multi, ".*").replace(single, "."); Pattern p = Pattern.compile(regex, flags); output.put((String) expr, p); return output; }</code><technical_language>I expect this sense ... handling remaining parts of filter below. Hold - do want check if expression is a propertyName a Literal first? I assuming is a propretyName, I occasionally Concat a big string of text descriptions searching of LIKE</technical_language>

Target:
public Object visit(PropertyIsLike filter, Object extraData) { BasicDBObject output = asDBObject(extraData); Expression filterExpression = filter.getExpression(); if (!(filterExpression instanceof PropertyName)) { throw new UnsupportedOperationException(); } String expr = convert(filterExpression.accept(this, null), String.class); String multi = filter.getWildCard(); String single = filter.getSingleChar(); int flags = (filter.isMatchingCase()) ? 0 : Pattern.CASE_INSENSITIVE; String regex = filter.getLiteral().replace(multi, ".*").replace(single, "."); Pattern p = Pattern.compile(regex, flags); output.put((String) expr, p); return output; }
Source:
<code>protected void doSomething(int i, Record record) throws IOException { assertEquals("0", record.getKey()); assertTrue(record.getData().length > 0); if (!writeToOuput) { return; } String message = new String(record.getData(), StandardCharsets.UTF_8); message = message.replace("logEntry", "XXX"); <START> Record changed = new Record(record.getKey(), message.getBytes(StandardCharsets.UTF_8), record.getWatermark(), <END> record.getFlags()); dataFileWriter.append(changed); }</code><technical_language>import statically UTF_8 a one-lined declaration</technical_language>

Target:
protected void doSomething(int i, Record record) throws IOException { assertEquals("0", record.getKey()); assertTrue(record.getData().length > 0); if (!writeToOuput) { return; } String message = new String(record.getData(), UTF_8); message = message.replace("logEntry", "XXX"); Record changed = new Record(record.getKey(), message.getBytes(UTF_8), record.getWatermark(), record.getFlags()); dataFileWriter.append(changed); }
Source:
<code>public void onReplaced(@Nonnull BlockState state, World world, @Nonnull BlockPos pos, BlockState newState, boolean moving) { if(state.getBlock()!=newState.getBlock()) { int dummyState = state.get(POST_SLAVE); HorizontalOffset offset = state.get(HORIZONTAL_OFFSET); if(dummyState > 0&&offset==HorizontalOffset.NONE) world.setBlockState(pos.down(dummyState), Blocks.AIR.getDefaultState()); else if(dummyState==0) { spawnAsEntity(world, pos, new ItemStack(this)); final int highestBlock = 3; BlockPos armStart = pos.up(highestBlock); for(Direction d : Direction.BY_HORIZONTAL_INDEX) { BlockPos armPos = armStart.offset(d); BlockState armState = world.getBlockState(armPos); if(armState.getBlock()==this&&armState.get(HORIZONTAL_OFFSET).getOffset().equals(d.getDirectionVec())) world.setBlockState(armPos, Blocks.AIR.getDefaultState()); } for(int i = 0; i <= highestBlock; ++i) world.setBlockState(pos.up(i), Blocks.AIR.getDefaultState()); } <START> super.onReplaced(state, world, pos, newState, moving); <END> } }</code><technical_language>this if</technical_language>

Target:
public void onReplaced(@Nonnull BlockState state, World world, @Nonnull BlockPos pos, BlockState newState, boolean moving) { if(state.getBlock()!=newState.getBlock()) { int dummyState = state.get(POST_SLAVE); HorizontalOffset offset = state.get(HORIZONTAL_OFFSET); if(dummyState > 0&&offset==HorizontalOffset.NONE) world.setBlockState(pos.down(dummyState), Blocks.AIR.getDefaultState()); else if(dummyState==0) { spawnAsEntity(world, pos, new ItemStack(this)); final int highestBlock = 3; BlockPos armStart = pos.up(highestBlock); for(Direction d : Direction.BY_HORIZONTAL_INDEX) { BlockPos armPos = armStart.offset(d); BlockState armState = world.getBlockState(armPos); if(armState.getBlock()==this&&armState.get(HORIZONTAL_OFFSET).getOffset().equals(d.getDirectionVec())) world.setBlockState(armPos, Blocks.AIR.getDefaultState()); } for(int i = 0; i <= highestBlock; ++i) world.setBlockState(pos.up(i), Blocks.AIR.getDefaultState()); } } super.onReplaced(state, world, pos, newState, moving); }
Source:
<code>public Observable<ChangeNotification<InstanceInfo>> changeNotifications() { <START> return aggregatedStream.share(); <END> }</code><technical_language>is need for channel contract guarantees single subscription only</technical_language>

Target:
public Observable<ChangeNotification<InstanceInfo>> changeNotifications() { return aggregatedStream; }
Source:
<code>protected HAClusterConfig(final Builder builder) { super(builder); data_sources = builder.dataSources == null ? Collections.emptyList() : builder.dataSources; data_source_configs = builder.dataSourceConfigs == null ? Collections.emptyList() : builder.dataSourceConfigs; merge_aggregator = builder.mergeAggregator; secondary_timeout = builder.secondaryTimeout; primary_timeout = builder.primaryTimeout; original_secondary_timeout = Strings.isNullOrEmpty(getOriginalsecondarytimeout()) ? secondary_timeout : getOriginalsecondarytimeout(); original_primary_timeout = Strings.isNullOrEmpty(getOriginalprimarytimeout()) ? primary_timeout : getOriginalprimarytimeout(); <START> hash = buildHashCode().asInt(); <END> if (!Strings.isNullOrEmpty(secondary_timeout)) { DateTime.parseDuration(secondary_timeout); } if (!Strings.isNullOrEmpty(primary_timeout)) { DateTime.parseDuration(primary_timeout); } }</code><technical_language>asLong();</technical_language>

Target:
protected HAClusterConfig(final Builder builder) { super(builder); data_sources = builder.dataSources == null ? Collections.emptyList() : builder.dataSources; data_source_configs = builder.dataSourceConfigs == null ? Collections.emptyList() : builder.dataSourceConfigs; merge_aggregator = builder.mergeAggregator; secondary_timeout = builder.secondaryTimeout; primary_timeout = builder.primaryTimeout; if (!Strings.isNullOrEmpty(secondary_timeout)) { DateTime.parseDuration(secondary_timeout); } if (!Strings.isNullOrEmpty(primary_timeout)) { DateTime.parseDuration(primary_timeout); } hash = buildHashCode().asInt(); }
Source:
<code>public String postBuildComment(AbstractBuild<?, ?> build, TaskListener listener) { <START> return "\nRefer to this link for build results (access rights to CI server needed): \n" + <END> generateCustomizedMessage(build) + "\n"; }</code><technical_language>StringBuilder is cleaner more readable. allows for easier expansion editing</technical_language>

Target:
public String postBuildComment(AbstractBuild<?, ?> build, TaskListener listener) { StringBuilder msg = new StringBuilder(); msg.append("\nRefer to this link for build results (access rights to CI server needed): \n"); msg.append(generateCustomizedMessage(build)); msg.append("\n"); return msg.toString(); }
Source:
<code>public static Collection<Thread> findThreads(final ThreadGroup group, final boolean recurse, final ThreadPredicate predicate) { if (group == null) { throw new IllegalArgumentException("The group must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate must not be null"); } <START> final List<Thread> result = new ArrayList<Thread>(); <END> int count = group.activeCount(); Thread[] threads; do { threads = new Thread[count + (count >> 1) + 1]; count = group.enumerate(threads, recurse); } while (count >= threads.length); for (int i = 0; i < count; ++i) { if (predicate.test(threads[i])) { result.add(threads[i]); } } return Collections.unmodifiableCollection(result); }</code><technical_language>If result is defined do while loop, initialised count initial capacity, avoid potential additional array allocation/copy invoking add()</technical_language>

Target:
public static Collection<Thread> findThreads(final ThreadGroup group, final boolean recurse, final ThreadPredicate predicate) { if (group == null) { throw new IllegalArgumentException("The group must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate must not be null"); } int count = group.activeCount(); Thread[] threads; do { threads = new Thread[count + (count / 2) + 1]; count = group.enumerate(threads, recurse); } while (count >= threads.length); final List<Thread> result = new ArrayList<Thread>(count); for (int i = 0; i < count; ++i) { if (predicate.test(threads[i])) { result.add(threads[i]); } } return Collections.unmodifiableCollection(result); }
Source:
<code>public void onInitAfterLoadTemplate(LiveStreamTranscoder liveStreamTranscoder) { TranscoderStream transcoderStream = liveStreamTranscoder.getTranscodingStream(); java.util.List<com.wowza.wms.transcoder.model.TranscoderStreamDestination> transcoderStreamsMap = transcoderStream.getDestinations(); IMediaStream stream = liveStreamTranscoder.getStream(); if (transcoderStreamsMap.size() == 0){ String msg = "Stream " + stream.getName() + " has no ingest in conversion profile"; logger.error(msg); <START> if (stream.getClient() != null){ <END> DiagnosticsProvider.addRejectedStreamFromClient(msg, stream.getClient()); } else if (stream.getRTPStream() != null && stream.getRTPStream().getSession() !=null){ DiagnosticsProvider.addRejectedStreamFromRTSP(msg, stream.getRTPStream().getSession()); } stream.shutdown(); stream.stopPublishing(); } }</code><technical_language>i move this logic DiagnosticsProvider (DiagnosticsProvider.addRejectedStream(ImediaStream, msg)</technical_language>

Target:
public void onInitAfterLoadTemplate(LiveStreamTranscoder liveStreamTranscoder) { TranscoderStream transcoderStream = liveStreamTranscoder.getTranscodingStream(); java.util.List<com.wowza.wms.transcoder.model.TranscoderStreamDestination> transcoderStreamsMap = transcoderStream.getDestinations(); IMediaStream stream = liveStreamTranscoder.getStream(); if (transcoderStreamsMap.size() == 0){ DiagnosticsProvider.addRejectedStream(stream, " has no ingest in conversion profile. Error: transcoderStreamsMap.size() = 0"); stream.shutdown(); stream.stopPublishing(); } }
Source:
<code>protected void init(long[] shape) { if (shape.length == 1) { rows = 1; <START> columns = (int) shape[0]; <END> } else if (this.shape().length == 2) { rows = (int) shape[0]; columns = (int) shape[1]; } rank = shape.length; }</code><technical_language>change long instead of casting</technical_language>

Target:
protected void init(long[] shape) { if (shape.length == 1) { rows = 1; columns = shape[0]; } else if (this.shape().length == 2) { rows = shape[0]; columns = shape[1]; } rank = shape.length; }
Source:
<code>private TaskAssigningSolution createTaskAssigningSolution(String fileName, int taskListSize, int groupListSize, int userListSize) { random = new Random(37); TaskAssigningSolution solution = new TaskAssigningSolution(); solution.setId(0L); List<Group> groupList = createGroupList(groupListSize); createUserList(solution, userListSize, groupList); createTaskList(solution, taskListSize, groupList); <START> BigInteger a = AbstractSolutionImporter.factorial(taskListSize + userListSize - 1); BigInteger b = AbstractSolutionImporter.factorial(userListSize - 1); <END> BigInteger possibleSolutionSize = (a == null || b == null) ? null : a.divide(b); logger.info("TaskAssigningSolution has tasks, groups, and users with a search space of {}.", fileName, taskListSize, groupListSize, userListSize, AbstractSolutionImporter.getFlooredPossibleSolutionSize(possibleSolutionSize)); return solution; }</code><technical_language>naming variable a b understanding purpose</technical_language>

Target:
private TaskAssigningSolution createTaskAssigningSolution(String fileName, int taskListSize, int groupListSize, int userListSize) { TaskAssigningSolution solution = new TaskAssigningSolution(); solution.setId(0L); List<Group> groupList = createGroupList(groupListSize); createUserList(solution, userListSize, groupList); createTaskList(solution, taskListSize, groupList); BigInteger totalFacts = AbstractSolutionImporter.factorial(taskListSize + userListSize - 1); BigInteger fixedFacts = AbstractSolutionImporter.factorial(userListSize - 1); BigInteger possibleSolutionSize = (totalFacts == null || fixedFacts == null) ? null : totalFacts.divide(fixedFacts); logger.info("TaskAssigningSolution has tasks, groups, and users with a search space of {}.", fileName, taskListSize, groupListSize, userListSize, AbstractSolutionImporter.getFlooredPossibleSolutionSize(possibleSolutionSize)); return solution; }
Source:
<code>protected void updateWeights(FeedbackQuestion question) { FeedbackQuestionAttributes attr = FeedbackQuestionAttributes.valueOf(question); FeedbackRubricQuestionDetails fqd = (FeedbackRubricQuestionDetails) attr.getQuestionDetails(); List<List<Double>> weightsForEachCell = fqd.getRubricWeights(); FeedbackQuestionsDb fqDb = new FeedbackQuestionsDb(); try { Field rubricWeightsForEachCell = fqd.getClass().getDeclaredField("rubricWeightsForEachCell"); rubricWeightsForEachCell.setAccessible(true); rubricWeightsForEachCell.set(fqd, weightsForEachCell); attr.setQuestionDetails(fqd); <START> fqDb.updateFeedbackQuestion(attr); <END> } catch (ReflectiveOperationException e) { System.out.println(e.getMessage()); } catch (InvalidParametersException e) { System.out.println(e.getMessage()); } catch (EntityDoesNotExistException e) { System.out.println(e.getMessage()); } }</code><technical_language>is fqDB fetch question update attribute. If set serialised JSON question.setQuestionText(attr.questionMetaData);, need fqDB</technical_language>

Target:
protected void updateWeights(FeedbackQuestion question) { FeedbackQuestionAttributes attr = FeedbackQuestionAttributes.valueOf(question); FeedbackRubricQuestionDetails fqd = (FeedbackRubricQuestionDetails) attr.getQuestionDetails(); List<List<Double>> weightsForEachCell = fqd.getRubricWeights(); try { Field rubricWeightsForEachCell = fqd.getClass().getDeclaredField("rubricWeightsForEachCell"); rubricWeightsForEachCell.setAccessible(true); rubricWeightsForEachCell.set(fqd, weightsForEachCell); attr.setQuestionDetails(fqd); question.setQuestionText(attr.questionMetaData); question.keepUpdateTimestamp = true; } catch (ReflectiveOperationException e) { System.out.println(e.getMessage()); } }
Source:
<code>public void run() { setPriority(Thread.NORM_PRIORITY); try { while ((currentJob = pool.startJob(this)) != null) { IStatus result = Status.OK_STATUS; try { <START> MonitorCancellationMonitoringPolicy monitorCancellationMonitoringPolicy <END> = JobManager.getInstance().getMonitorCancellationMonitoringPolicy(); if (monitorCancellationMonitoringPolicy != null && monitorCancellationMonitoringPolicy.enabled()) { CancelCheckMonitor pm = new CancelCheckMonitor(currentJob.getProgressMonitor(), monitorCancellationMonitoringPolicy); currentJob.setProgressMonitor(pm); result = currentJob.run(pm.willStart()); pm.hasStopped(); IStatus cancelStatus = checkCancel(currentJob, pm, monitorCancellationMonitoringPolicy); if (!cancelStatus.isOK()) { RuntimeLog.log(cancelStatus); } } else { result = currentJob.run(currentJob.getProgressMonitor()); } } catch (OperationCanceledException e) { result = Status.CANCEL_STATUS; } catch (Exception e) { result = handleException(currentJob, e); } catch (ThreadDeath e) { result = handleException(currentJob, e); throw e; } catch (Error e) { result = handleException(currentJob, e); } finally { Thread.interrupted(); if (result == null) result = handleException(currentJob, new NullPointerException()); pool.endJob(currentJob, result); currentJob = null; setPriority(Thread.NORM_PRIORITY); } } } catch (Throwable t) { RuntimeLog.log(new Status(IStatus.ERROR, JobManager.PI_JOBS, JobManager.PLUGIN_ERROR, "Unhandled error", t)); } finally { currentJob = null; pool.endWorker(this); } }</code><technical_language>this code related monitoring moved a helper class orthogonal else Worker does</technical_language>

Target:
public void run() { setPriority(Thread.NORM_PRIORITY); try { while ((currentJob = pool.startJob(this)) != null) { IStatus result = Status.OK_STATUS; try { JobCancelabilityMonitor.Options jobCancelabilityMonitorOptions = JobManager.getInstance().getJobCancelabilityMonitorOptions(); if (jobCancelabilityMonitorOptions != null && jobCancelabilityMonitorOptions.enabled()) { result = runWithCancelabilityMonitoring(jobCancelabilityMonitorOptions); } else { result = currentJob.run(currentJob.getProgressMonitor()); } } catch (OperationCanceledException e) { result = Status.CANCEL_STATUS; } catch (Exception e) { result = handleException(currentJob, e); } catch (ThreadDeath e) { result = handleException(currentJob, e); throw e; } catch (Error e) { result = handleException(currentJob, e); } finally { Thread.interrupted(); if (result == null) result = handleException(currentJob, new NullPointerException()); pool.endJob(currentJob, result); currentJob = null; setPriority(Thread.NORM_PRIORITY); } } } catch (Throwable t) { RuntimeLog.log(new Status(IStatus.ERROR, JobManager.PI_JOBS, JobManager.PLUGIN_ERROR, "Unhandled error", t)); } finally { currentJob = null; pool.endWorker(this); } }
Source:
<code>public int fetchUniformLocation (String name, boolean pedantic) { GL20 gl = Gdx.gl20; int location; if ((location = uniforms.get(name, -2)) == -2) { location = gl.glGetUniformLocation(program, name); if (location == -1 && pedantic) { if (isCompiled) throw new IllegalArgumentException("no uniform with name '" + name + "' in shader"); <START> else throw new GdxRuntimeException("An attempted fetch uniform from uncompiled shader \n" + getLog()); <END> } uniforms.put(name, location); } return location; }</code><technical_language>IllegalStateException fit GdxRuntimeException</technical_language>

Target:
public int fetchUniformLocation (String name, boolean pedantic) { GL20 gl = Gdx.gl20; int location; if ((location = uniforms.get(name, -2)) == -2) { location = gl.glGetUniformLocation(program, name); if (location == -1 && pedantic) { if (isCompiled) throw new IllegalArgumentException("no uniform with name '" + name + "' in shader"); throw new IllegalStateException("An attempted fetch uniform from uncompiled shader \n" + getLog()); } uniforms.put(name, location); } return location; }
Source:
<code>public CqlResult( Result result, Set<SearchTerm> searchTerms, QueryRequest queryRequest, boolean normalize, FilterAdapter filterAdapter, ActionRegistry actionRegistry) { Metacard mc = result.getMetacard(); hasThumbnail = Optional.of(mc).map(Metacard::getThumbnail).map(thumb -> thumb.length > 0).orElse(false); isResourceLocal = Optional.of(mc) .map(m -> m.getAttribute("internal.local-resource")) .map(Attribute::getValue) .filter(Boolean.class::isInstance) .map(Boolean.class::cast) .orElse(false); distance = normalizeDistance(result, queryRequest.getQuery(), filterAdapter); relevance = result.getRelevanceScore(); if (normalize) { countMatches(searchTerms, mc); } actions = actionRegistry .list(result.getMetacard()) .stream() <START> .map(cqlResult -> new CqlAction(cqlResult, cqlResult.getId())) <END> .collect(Collectors.toList()); metacard = metacardToMap(result); }</code><technical_language>object mapped is Action parameter called action</technical_language>

Target:
public CqlResult( Result result, Set<SearchTerm> searchTerms, QueryRequest queryRequest, boolean normalize, FilterAdapter filterAdapter, ActionRegistry actionRegistry) { Metacard mc = result.getMetacard(); hasThumbnail = Optional.of(mc).map(Metacard::getThumbnail).map(thumb -> thumb.length > 0).orElse(false); isResourceLocal = Optional.of(mc) .map(m -> m.getAttribute("internal.local-resource")) .map(Attribute::getValue) .filter(Boolean.class::isInstance) .map(Boolean.class::cast) .orElse(false); distance = normalizeDistance(result, queryRequest.getQuery(), filterAdapter); relevance = result.getRelevanceScore(); if (normalize) { countMatches(searchTerms, mc); } actions = actionRegistry .list(result.getMetacard()) .stream() .map(action -> new DisplayableAction(action, action.getId())) .collect(Collectors.toList()); metacard = metacardToMap(result); }
Source:
<code>protected void processIncoming() throws IOException, ClientConnectionException { <START> ByteBuffer buffer = ByteBuffer.allocate(16384); <END> int read = readBuffer(buffer); if (read <= 0) { return; } ByteBuffer messages = getCompleteMessages(buffer); if (messages.position() > 0){ messages.rewind(); emitOnMessageReceived(messages.array()); } if (buffer.position() > 0) { ByteBuffer acc = ByteBuffer.allocate(this.ibuff.limit() + buffer.limit()); acc.put(this.ibuff); acc.put(buffer); this.ibuff = acc; } else { this.ibuff = ByteBuffer.allocate(0); } }</code><technical_language>do reallocating this buffer for read</technical_language>

Target:
protected abstract void processIncoming() throws IOException, ClientConnectionException; protected void processOutgoing() throws IOException, ClientConnectionException { final ByteBuffer buff = outbox.peekLast(); if (buff == null) { return; } writeBuffer(buff); if (!buff.hasRemaining()) { outbox.removeLast(); } updateInterestedOps(); }
Source:
<code>public static void install() throws Exception { Field fieldStatusHandler = StatusManager.class.getDeclaredField("statusHandler"); fieldStatusHandler.setAccessible(true); <START> fieldStatusHandler.set(StatusManager.getManager(), new TestStatusHandler()); <END> }</code><technical_language>I read existing set in ininstall. This avoids sirprises for others assuming handler is installed is this test</technical_language>

Target:
public static void install() throws Exception { if (isInstalled) { return; } Field fieldStatusHandler = StatusManager.class.getDeclaredField("statusHandler"); fieldStatusHandler.setAccessible(true); StatusManager statusManager = StatusManager.getManager(); originalInstance = fieldStatusHandler.get(statusManager); fieldStatusHandler.set(statusManager, new TestStatusHandler()); fieldStatusHandler.setAccessible(false); isInstalled = true; }
Source:
<code>private static Map<String, String> dataMapToQueryParams(DataMap dataMap) { final Map<String, String> result = encodeDataMapParameters(dataMap); for (final String parameterName : RestConstants.PROJECTION_PARAMETERS) { if (dataMap.containsKey(parameterName)) { <START> try <END> { result.put(parameterName, dataMap.getString(parameterName)); } catch (ClassCastException exception) { result.put(parameterName, URIMaskUtil.encodeMaskForURI(dataMap.getDataMap(parameterName))); } } } return result; }</code><technical_language>try-catches dictate normal logic flow (rather for exceptions) is bad practice. I suggest retrieving generic object map checking type. this is IMO</technical_language>

Target:
private static Map<String, String> dataMapToQueryParams(DataMap dataMap) { final Map<String, String> result = encodeDataMapParameters(dataMap); for (final String parameterName : RestConstants.PROJECTION_PARAMETERS) { if (dataMap.containsKey(parameterName)) { Object projectionParameters = dataMap.get(parameterName); if (projectionParameters instanceof String) { result.put(parameterName, (String) projectionParameters); } else if (projectionParameters instanceof DataMap) { result.put(parameterName, URIMaskUtil.encodeMaskForURI((DataMap) projectionParameters)); } else { throw new IllegalArgumentException("Invalid projection field data type"); } } } return result; }
Source:
<code>private List<AssetRecord> determineWritingChannels(final WireRecord record) { <START> requireNonNull(record, message.wireRecordsNonNull()); <END> final List<AssetRecord> assetRecordsToWriteChannels = CollectionUtil.newArrayList(); final Map<Long, Channel> channels = this.assetConfiguration.getAssetChannels(); for (final Entry<Long, Channel> channelEntry : channels.entrySet()) { final Channel channel = channelEntry.getValue(); final String channelName = channel.getName(); final ChannelType channelType = channel.getType(); if (channelType != WRITE && channelType != READ_WRITE) { continue; } Map<String, TypedValue<?>> wireRecordProperties = record.getProperties(); if (wireRecordProperties.containsKey(channelName)) { final TypedValue<?> value = wireRecordProperties.get(channelName); if (channel.getValueType() == value.getType()) { assetRecordsToWriteChannels.add(prepareAssetRecord(channel, value)); } } } return assetRecordsToWriteChannels; }</code><technical_language>change wireRecordNonNull() change localization string literal</technical_language>

Target:
private List<AssetRecord> determineWritingChannels(final WireRecord record) { requireNonNull(record, message.wireRecordNonNull()); final List<AssetRecord> assetRecordsToWriteChannels = CollectionUtil.newArrayList(); final Map<Long, Channel> channels = this.assetConfiguration.getAssetChannels(); for (final Entry<Long, Channel> channelEntry : channels.entrySet()) { final Channel channel = channelEntry.getValue(); final String channelName = channel.getName(); final ChannelType channelType = channel.getType(); if (channelType != WRITE && channelType != READ_WRITE) { continue; } Map<String, TypedValue<?>> wireRecordProperties = record.getProperties(); if (wireRecordProperties.containsKey(channelName)) { final TypedValue<?> value = wireRecordProperties.get(channelName); if (channel.getValueType() == value.getType()) { assetRecordsToWriteChannels.add(prepareAssetRecord(channel, value)); } } } return assetRecordsToWriteChannels; }
Source:
<code><START> protected boolean takeCharge(@Nonnull Location l) { <END> if (isChargeable()) { if (getCharge(l) < getEnergyConsumption()) { return false; } removeCharge(l, getEnergyConsumption()); } return true; }</code><technical_language>this is a "protected" method, Non-nullability of this parameter enforced Validate.notNull(l, message)</technical_language>

Target:
protected boolean takeCharge(@Nonnull Location l) { Validate.notNull(l, "Can't attempt to take charge from a null location!"); if (isChargeable()) { if (getCharge(l) < getEnergyConsumption()) { return false; } removeCharge(l, getEnergyConsumption()); } return true; }
Source:
<code>public InputStream getData() { switch (this.getUri().getScheme()) { case "http": case "https": try { final HttpURLConnection conn = (HttpURLConnection) this.uri.toURL().openConnection(); conn.setRequestMethod("GET"); this.headers.forEach(conn::setRequestProperty); conn.connect(); return conn.getInputStream(); } catch (final IOException e) { throw new RuntimeIOException("Could not retrieve data from block", e); } case "data": final String dataUri = this.uri.toString(); if (!dataUri.matches("^data:.*;base64,.*")) { throw new IllegalArgumentException("data URI must be base64 encoded: " + dataUri); } return new ByteArrayInputStream( Base64.getDecoder().decode(dataUri.replaceFirst("^data:.*;base64,", ""))); default: <START> throw new IllegalArgumentException("Unrecognized URI scheme in data block: " + this.uri.getScheme()); <END> } }</code><technical_language>IllegalArgumentException right. IllegalState new HtsgetMalformedResponseException that</technical_language>

Target:
public InputStream getData() { switch (this.getUri().getScheme()) { case "http": case "https": try { final HttpURLConnection conn = (HttpURLConnection) this.uri.toURL().openConnection(); conn.setRequestMethod("GET"); this.headers.forEach(conn::setRequestProperty); conn.connect(); return conn.getInputStream(); } catch (final IOException e) { throw new RuntimeIOException("Could not retrieve data from block", e); } case "data": final String dataUri = this.uri.toString(); if (!dataUri.matches("^data:.*;base64,.*")) { throw new HtsgetMalformedResponseException("data URI must be base64 encoded: " + dataUri); } return new ByteArrayInputStream( Base64.getDecoder().decode(dataUri.replaceFirst("^data:.*;base64,", ""))); default: throw new HtsgetMalformedResponseException("Unrecognized URI scheme in data block: " + this.uri.getScheme()); } }
Source:
<code>private void showHideJoinDashPayAction() { final Coin walletBalance = wallet.getBalance(Wallet.BalanceType.ESTIMATED); boolean canAffordIt = walletBalance.isGreaterThan(Constants.DASH_PAY_FEE) || walletBalance.equals(Constants.DASH_PAY_FEE); <START> boolean visible = true ; END> joinDashPayAction.setVisibility(visible ? View.VISIBLE : View.GONE); findViewById(R.id.join_dashpay_action_space).setVisibility(joinDashPayAction.getVisibility()); }</code><technical_language>change this, change later</technical_language>

Target:
private void showHideJoinDashPayAction() { if (syncComplete) { final Coin walletBalance = wallet.getBalance(Wallet.BalanceType.ESTIMATED); boolean canAffordIt = walletBalance.isGreaterThan(Constants.DASH_PAY_FEE) || walletBalance.equals(Constants.DASH_PAY_FEE); boolean visible = canAffordIt && config.getShowJoinDashPay(); joinDashPayAction.setVisibility(visible ? View.VISIBLE : View.GONE); } else { joinDashPayAction.setVisibility(View.GONE); } findViewById(R.id.join_dashpay_action_space).setVisibility(joinDashPayAction.getVisibility()); }
Source:
<code>public Brand createOrUpdateBrand(ModelWithPayload<String> uriWithPayload) { String uri = uriWithPayload.getModel(); <START> Object payload = (uriWithPayload.getPayload() != null) ? uriWithPayload.getPayload() : ""; <END> Preconditions.checkArgument(canFetch(uri), "Cannot fetch C4 uri: %s as it is not in the expected format: %s",uri, BRAND_PAGE_PATTERN.toString()); try { log.info("Fetching C4 brand " + uri); Optional<Feed> source = feedClient.brandFeed(uri); if (source.isPresent()) { BrandSeriesAndEpisodes brandHierarchy = extractor.extract(source.get()); Brand brand = resolveAndUpdate(brandHierarchy.getBrand()); checkUri(brand); checkSource(brand); writer.createOrUpdate(brand, payload); write(brandHierarchy.getSeriesAndEpisodes(), brand); return brandHierarchy.getBrand(); } throw new FetchException("Failed to fetch " + uri); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>this null, change createOrUpdateMethods allow nullable payloads. If is telescope serialisation step payloads add null checking stage</technical_language>

Target:
public Brand createOrUpdateBrand(ModelWithPayload<String> uriWithPayload) { String uri = uriWithPayload.getModel(); Preconditions.checkArgument(canFetch(uri), "Cannot fetch C4 uri: %s as it is not in the expected format: %s",uri, BRAND_PAGE_PATTERN.toString()); try { log.info("Fetching C4 brand " + uri); Optional<Feed> source = feedClient.brandFeed(uri); if (source.isPresent()) { BrandSeriesAndEpisodes brandHierarchy = extractor.extract(source.get()); Brand brand = resolveAndUpdate(brandHierarchy.getBrand()); checkUri(brand); checkSource(brand); writer.createOrUpdate(brand, uriWithPayload.getPayload()); write(brandHierarchy.getSeriesAndEpisodes(), brand); return brandHierarchy.getBrand(); } throw new FetchException("Failed to fetch " + uri); } catch (Exception e) { throw new RuntimeException(e); } }