auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized void setCapacity(int newNumExecutors, int newWaitQueueSize) { <START> if (newNumExecutors > configuredMaxExecutors) { <END> throw new IllegalArgumentException("Requested newNumExecutors=" + newNumExecutors + " is greater than the configured maximum=" + configuredMaxExecutors); } if (newWaitQueueSize > configuredWaitingQueueSize) { throw new IllegalArgumentException("Requested newWaitQueueSize=" + newWaitQueueSize + " is greater than the configured maximum=" + configuredWaitingQueueSize); } numSlotsAvailable.addAndGet(newNumExecutors - maxParallelExecutors); maxParallelExecutors = newNumExecutors; waitQueue.setWaitQueueSize(newWaitQueueSize); LOG.info("TaskExecutorService is setting capacity to: numExecutors=" + newNumExecutors + ", waitQueueSize=" + newWaitQueueSize); }</code><technical_language>verify new values >= zero</technical_language>

Target:
public synchronized void setCapacity(int newNumExecutors, int newWaitQueueSize) { if (newNumExecutors > configuredMaxExecutors) { throw new IllegalArgumentException("Requested newNumExecutors=" + newNumExecutors + " is greater than the configured maximum=" + configuredMaxExecutors); } if (newWaitQueueSize > configuredWaitingQueueSize) { throw new IllegalArgumentException("Requested newWaitQueueSize=" + newWaitQueueSize + " is greater than the configured maximum=" + configuredWaitingQueueSize); } if (newNumExecutors < 0) { throw new IllegalArgumentException("Negative numExecutors is not allowed. Requested " + "newNumExecutors=" + newNumExecutors); } if (newWaitQueueSize < 0) { throw new IllegalArgumentException("Negative waitQueueSize is not allowed. Requested " + "newWaitQueueSize=" + newWaitQueueSize); } numSlotsAvailable.addAndGet(newNumExecutors - maxParallelExecutors); maxParallelExecutors = newNumExecutors; waitQueue.setWaitQueueSize(newWaitQueueSize); LOG.info("TaskExecutorService is setting capacity to: numExecutors=" + newNumExecutors + ", waitQueueSize=" + newWaitQueueSize); }
Source:
<code>public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { Map<String, String> retMap = super.getEventHoverToolTipInfo(event, hoverTime); if (retMap == null) { retMap = new LinkedHashMap<>(1); } if (!(event instanceof TimeEvent) || !((TimeEvent) event).hasValue() || !(event.getEntry() instanceof ControlFlowEntry)) { return retMap; } ControlFlowEntry entry = (ControlFlowEntry) event.getEntry(); ThreadStatusDataProvider dataProvider <START> = (ThreadStatusDataProvider) AbstractDataProviderTimeGraphView.getProvider(entry); <END> TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> response = dataProvider.fetchTooltip( new SelectionTimeQueryFilter(hoverTime, hoverTime, 1, Collections.singletonList(entry.getModel().getId())), null); Map<@NonNull String, @NonNull String> map = response.getModel(); if (map != null) { String cpu = map.get(ThreadStatusDataProvider.CPU); if (cpu != null) { retMap.put(Messages.ControlFlowView_attributeCpuName, cpu); } } return retMap; }</code><technical_language>class type check</technical_language>

Target:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { Map<String, String> retMap = super.getEventHoverToolTipInfo(event, hoverTime); if (retMap == null) { retMap = new LinkedHashMap<>(1); } if (!(event instanceof TimeEvent) || !((TimeEvent) event).hasValue() || !(event.getEntry() instanceof ControlFlowEntry)) { return retMap; } ControlFlowEntry entry = (ControlFlowEntry) event.getEntry(); ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = BaseDataProviderTimeGraphView.getProvider(entry); TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> response = dataProvider.fetchTooltip( new SelectionTimeQueryFilter(hoverTime, hoverTime, 1, Collections.singletonList(entry.getModel().getId())), null); Map<@NonNull String, @NonNull String> map = response.getModel(); if (map != null) { String cpu = map.get(ThreadStatusDataProvider.CPU); if (cpu != null) { retMap.put(Messages.ControlFlowView_attributeCpuName, cpu); } } return retMap; }
Source:
<code>public void addBindingProvider(BindingProvider provider) { super.addBindingProvider(provider); <START> logger.debug("addBindingProvider: " + Arrays.toString(provider.getItemNames().toArray())); <END> for (String itemName: provider.getItemNames()) { bindGpioPin((MCP23017BindingProvider)provider, itemName); } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void addBindingProvider(BindingProvider provider) { super.addBindingProvider(provider); logger.debug("addBindingProvider: {}", Arrays.toString(provider.getItemNames().toArray())); for (String itemName : provider.getItemNames()) { bindGpioPin((MCP23017BindingProvider) provider, itemName); } }
Source:
<code>private Map<Path, String> getPaths(String pathWithWildcard) { String pathWithoutWildcards = pathWithWildcard.replace("*", ""); try { Map<Path, String> paths = Files.list(Paths.get(pathWithoutWildcards)) .filter(path -> path.toString().toLowerCase().endsWith(".jar")) .collect(Collectors.toMap(p -> p, o -> o.getFileName().toString())); if (paths == null || paths.isEmpty()) { <START> throw new IllegalStateException("Cannot find any jars files in selected path"); <END> } return paths; } catch (IOException e) { throw new IllegalStateException("Cannot find any jars files in selected path"); } }</code><technical_language>discussed, this exception is inappropriate for user errors. a conditional</technical_language>

Target:
private Map<Path, String> getPaths(String pathWithWildcard) { String pathWithoutWildcards = pathWithWildcard.replace("*", ""); try { return Files.list(Paths.get(pathWithoutWildcards)) .filter(path -> path.toString().toLowerCase().endsWith(".jar")) .collect(Collectors.toMap(p -> p, o -> o.getFileName().toString())); } catch (IOException e) { throw new IllegalStateException("Cannot find any jars files in selected path"); } }
Source:
<code>public List<IMetric> transform(List<IMetric> metrics) <START> { <END> if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); AveragedMetric workingMetric = new AveragedMetric(metrics.get(0)); ArrayList<IMetric> aggedMetrics = new ArrayList<IMetric>(); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { aggedMetrics.add(workingMetric); workingMetric = new AveragedMetric(curMetric); } else { workingMetric.addDataPoint(curMetric.getValue()); } } return aggedMetrics; }</code><technical_language>is this meant override IMetricSetTransformer.transform()? If so, annotate @Override</technical_language>

Target:
public List<IMetric> transform(List<IMetric> metrics) { if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); ArrayList<IMetric> aggedMetrics = new ArrayList<IMetric>(); AveragedMetric workingMetric = new AveragedMetric(metrics.get(0)); aggedMetrics.add(workingMetric); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { workingMetric = new AveragedMetric(curMetric); aggedMetrics.add(workingMetric); } else { workingMetric.addDataPoint(curMetric.getValue()); } } return aggedMetrics; }
Source:
<code>public void setup(OperatorContext context) { <START> valueList = new ArrayList<Map<String, T>>(); <END> HashMap<String, T> map = new HashMap<>(); map.put(valueName, null); valueList.add(map); }</code><technical_language>consider Collections.singletonList()</technical_language>

Target:
public void setup(OperatorContext context) { valueMap = new HashMap<>(); valueMap.put(valueName, null); valueList = Collections.singletonList(valueMap); }
Source:
<code>public boolean isAbstract() { <START> return true; <END> }</code><technical_language>This return false if method is declared default keyword is static</technical_language>

Target:
public boolean isAbstract() { if (isDefault() || isStatic()) { return false; } else { return true; } }
Source:
<code>public void whenGetOptionsRetentionTimeExist() throws Exception { final EventType defaultEventType = buildDefaultEventType(); final EventTypeOptions eventTypeOptions = new EventTypeOptions(); eventTypeOptions.setRetentionTime(150L); defaultEventType.setOptions(eventTypeOptions); Mockito.doReturn(Collections.singletonList(defaultEventType)).when(eventTypeRepository).list(); <START> getEventType() <END> .andExpect(status().is2xxSuccessful()) .andExpect(content().string(new StringContains("\"options\":{\"retention_time\":150}"))); }</code><technical_language>get a list of of event types? I more straightforward if get a single event type, .andExpect(jsonPath("$.options.retention_time", equalTo(150))) instead of StringContains matching</technical_language>

Target:
public void whenGetOptionsRetentionTimeExist() throws Exception { final EventType defaultEventType = buildDefaultEventType(); defaultEventType.getOptions().setRetentionTime(TOPIC_RETENTION_TIME_MS); final String eventTypeName = defaultEventType.getName(); Mockito.doReturn(defaultEventType).when(eventTypeRepository).findByName(eventTypeName); getEventType(eventTypeName) .andExpect(status().is2xxSuccessful()) .andExpect(content().string(new StringContains("\"options\":{\"retention_time\":150}"))); }
Source:
<code>public HashMap<Integer, ArchitectureType> getOsArchitectures() { HashMap<Integer, ArchitectureType> osArchitectures = new HashMap<Integer, ArchitectureType>(); for (int osId : getOsIds()) { String architecture = getValueByVersion(idToUnameLookup.get(osId), "cpuArchitecture", null); ArchitectureType archType = ArchitectureType.valueOf(architecture); <START> if (architecture != null) { <END> osArchitectures.put(osId, archType); } } return osArchitectures; }</code><technical_language>careful calling ArchitectureType.valueOf(architecture) if architecture null - fail NPE. Please move null check</technical_language>

Target:
public HashMap<Integer, ArchitectureType> getOsArchitectures() { HashMap<Integer, ArchitectureType> osArchitectures = new HashMap<Integer, ArchitectureType>(); for (int osId : getOsIds()) { String architecture = getValueByVersion(idToUnameLookup.get(osId), "cpuArchitecture", null); if (architecture != null) { osArchitectures.put(osId, ArchitectureType.valueOf(architecture)); } } return osArchitectures; }
Source:
<code>public void onCompleted(Object companion) { <START> AppLog.i(AppLog.T.READER, "notifications update job service > all tasks completed"); <END> jobFinished((JobParameters) companion, false); }</code><technical_language>This AppLog.T. NOTIFS AppLog.T.READER (there instances of this)</technical_language>

Target:
public void onCompleted(Object companion) { AppLog.i(AppLog.T.NOTIFS, "notifications update job service > all tasks completed"); jobFinished((JobParameters) companion, false); }
Source:
<code>public static boolean isUpperCamelCase(String word) { <START> return !word.isEmpty() && word.matches(ALPHANUMERIC_REGEX) && Character.isUpperCase(word.charAt(0)); <END> }</code><technical_language>Performing a regex match is more computationally expensive isUpperCase() call short-circuited possible. switch order of word.matches() isUpperCase() advantage of this</technical_language>

Target:
public static boolean isUpperCamelCase(String word) { return !word.isEmpty() && Character.isUpperCase(word.charAt(0)) && word.matches(ALPHANUMERIC_REGEX); }
Source:
<code>public void applySelector(ClientSelector newSelector) { logger.info("Applying a new client selector :" + newSelector); clientSelector = newSelector; Collection<ClientEndpoint> endpoints = endpointManager.getEndpoints(); for (ClientEndpoint endpoint : endpoints) { if (clientSelector.select(endpoint)) { continue; } String clientUuid = endpoint.getUuid(); String memberUuid = ownershipMappings.get(clientUuid); ClientDisconnectionOperation op = new ClientDisconnectionOperation(clientUuid, memberUuid); InternalOperationService service = nodeEngine.getOperationService(); Address thisAddress = getThisAddress(); Future future = service.createInvocationBuilder(ClientEngineImpl.SERVICE_NAME, op, thisAddress).invoke(); try { future.get(); } catch (Exception e) { <START> logger.warning("Could not applied new selector for " + endpoint); <END> } } }</code><technical_language>A typo. apply..</technical_language>

Target:
public void applySelector(ClientSelector newSelector) { logger.info("Applying a new client selector :" + newSelector); clientSelector = newSelector; Collection<ClientEndpoint> endpoints = endpointManager.getEndpoints(); for (ClientEndpoint endpoint : endpoints) { if (clientSelector.select(endpoint)) { continue; } String clientUuid = endpoint.getUuid(); String memberUuid = ownershipMappings.get(clientUuid); ClientDisconnectionOperation op = new ClientDisconnectionOperation(clientUuid, memberUuid); InternalOperationService service = nodeEngine.getOperationService(); Address thisAddress = getThisAddress(); Future future = service.createInvocationBuilder(ClientEngineImpl.SERVICE_NAME, op, thisAddress).invoke(); try { future.get(); } catch (Exception e) { logger.warning("Could not apply new selector for " + endpoint); } } }
Source:
<code>public byte[] writeCleanUp(Set<String> removedIds){ CeleryBody body = new CeleryBody(); <START> body.task= "cleanup"; <END> body.expires=""; body.id="entity-CU:"+System.currentTimeMillis(); body.kwargs.put("cleanup_entities", removedIds); return writer.asCeleryTask(body); }</code><technical_language>I a linter for java projects yet, do if try follow some basic formatting rules, common for languages? spaces = + for example</technical_language>

Target:
public byte[] writeCleanUp(Set<String> removedIds) { CeleryBody body = new CeleryBody(); body.task = "cleanup"; body.expires = ""; String uuid = UUID.randomUUID().toString(); body.id = "entity-CU:" + uuid; body.kwargs.put("cleanup_entities", removedIds); CeleryBody.EntityCleanUpArg command = new CeleryBody.EntityCleanUpArg(); command.check_id = "CU:" + uuid; body.args.add(command); body.timelimit.add(3600L); body.timelimit.add(7200L); return writer.asCeleryTask(body); }
Source:
<code>Bundle toBundle() { Bundle bundle = new Bundle(); bundle.putString(KEY_SENDER_CONTACT_ID, senderContactId); bundle.putString(KEY_CONVERSATION_ID, conversId); bundle.putLong(KEY_TIMESTAMP, timestamp); bundle.putString(KEY_MESSAGE, message); bundle.putBundle(KEY_EXTRAS, bundle); return bundle; <START> }} <END></code><technical_language>Please separate lines</technical_language>

Target:
Bundle toBundle() { Bundle bundle = new Bundle(); bundle.putString(KEY_SENDER_CONTACT_ID, senderContactId); bundle.putString(KEY_CONVERSATION_ID, conversId); bundle.putLong(KEY_TIMESTAMP, timestamp); bundle.putString(KEY_MESSAGE, message); bundle.putBundle(KEY_EXTRAS, bundle); return bundle; }
Source:
<code>public void trade() { for (String stock : sellOrders.keySet()) { if (buyOrders.containsKey(stock)==false) { return; } ArrayList<Order> buying = buyOrders.get(stock); ArrayList<Order> selling = sellOrders.get(stock); TreeMap<Double, ArrayList<Order>> sortedOrders = new TreeMap<Double, ArrayList<Order>>(); sortOrder(buying, selling, sortedOrders); double marketPrice = m.getStockForSymbol(stock).getPrice(); ArrayList<Order> marketOrders = sortedOrders.remove(0.0); int <START> sumofBuy = <END> 0, sumofSell = 0; for (Order marketOrder : marketOrders) { if (marketOrder instanceof BuyOrder) { sumofBuy += marketOrder.getSize(); } else { sumofSell += marketOrder.getSize(); } } int priceSize = sortedOrders.size(); int[] sumBuyPrice = new int[priceSize]; int[] sumSellPrice = new int[priceSize]; cumulativeSellOrders(sortedOrders, sumofBuy, sumofSell, priceSize, sumBuyPrice, sumSellPrice); double matchingPrice = matchPrice(sortedOrders, marketPrice, priceSize, sumBuyPrice, sumSellPrice); updatePrice(stock, marketPrice, matchingPrice); delTrades(stock, sortedOrders, marketOrders, matchingPrice); } }</code><technical_language>o capital! sumOfBuy</technical_language>

Target:
public void trade() { for (String stock : sellOrders.keySet()) { if (buyOrders.containsKey(stock)==false) { return; } ArrayList<Order> buying = buyOrders.get(stock); ArrayList<Order> selling = sellOrders.get(stock); TreeMap<Double, ArrayList<Order>> sortedOrders = new TreeMap<Double, ArrayList<Order>>(); sortOrder(buying, selling, sortedOrders); double marketPrice = m.getStockForSymbol(stock).getPrice(); ArrayList<Order> marketOrders = sortedOrders.remove(0.0); int sumOfBuy = 0, sumOfSell = 0; for (Order marketOrder : marketOrders) { if (marketOrder instanceof BuyOrder) { sumOfBuy += marketOrder.getSize(); } else { sumOfSell += marketOrder.getSize(); } } int priceSize = sortedOrders.size(); int[] sumBuyPrice = new int[priceSize]; int[] sumSellPrice = new int[priceSize]; cumulativeSellOrders(sortedOrders, sumOfBuy, sumOfSell, priceSize, sumBuyPrice, sumSellPrice); double matchingPrice = matchPrice(sortedOrders, marketPrice, priceSize, sumBuyPrice, sumSellPrice); updatePrice(stock, marketPrice, matchingPrice); delTrades(stock, sortedOrders, marketOrders, matchingPrice); } }
Source:
<code>public void setupJob(JobContext context) throws IOException { try (DurationInfo d = new DurationInfo(LOG, "Job %s setting up", getUUID())) { jobSetup = true; Configuration c = context.getConfiguration(); c.set(FS_S3A_COMMITTER_UUID, this.getUUID()); if (getUUIDSource() == JobUUIDSource.GeneratedLocally) { <START> c.set(SPARK_WRITE_UUID, this.getUUID()); <END> } Path dest = getOutputPath(); if (createJobMarker){ commitOperations.deleteSuccessMarker(dest); } getDestFS().mkdirs(dest); warnOnActiveUploads(dest); } }</code><technical_language>odd set Spark property. else this</technical_language>

Target:
public void setupJob(JobContext context) throws IOException { try (DurationInfo d = new DurationInfo(LOG, "Job %s setting up", getUUID())) { jobSetup = true; Configuration c = context.getConfiguration(); c.set(FS_S3A_COMMITTER_UUID, getUUID()); c.set(FS_S3A_COMMITTER_UUID_SOURCE, getUUIDSource().getText()); Path dest = getOutputPath(); if (createJobMarker){ commitOperations.deleteSuccessMarker(dest); } getDestFS().mkdirs(dest); warnOnActiveUploads(dest); } }
Source:
<code>public void learn(int numIters, Map<String, List<Evaluation>> evaluations) { LogInfo.begin_track("Learner.learn()"); if (!params.isEmpty()) sortOnFeedback(); for (int iter = 0; iter <= numIters; iter++) { LogInfo.begin_track("Iteration %s/%s", iter, numIters); Execution.putOutput("iter", iter); Map<String, Evaluation> meanEvaluations = Maps.newHashMap(); for (String group : dataset.groups()) meanEvaluations.put(group, new Evaluation()); for (String group : dataset.groups()) { boolean lastIter = (iter == numIters); boolean updateWeights = opts.updateWeights && group.equals("train") && !lastIter; <START> if (parser instanceof MutatingParser) { <END> ((MutatingParser) parser).mutate(iter, numIters, group); } Evaluation eval = processExamples( iter, group, dataset.examples(group), updateWeights); MapUtils.addToList(evaluations, group, eval); meanEvaluations.get(group).add(eval); StopWatchSet.logStats(); } String path = Execution.getFile("params." + iter); if (path != null) { params.write(path); Utils.systemHard("ln -sf params." + iter + " " + Execution.getFile("params")); } LogInfo.end_track(); } LogInfo.end_track(); }</code><technical_language>If do this, mutate function part of Parser overridable function..</technical_language>

Target:
public void learn(int numIters, Map<String, List<Evaluation>> evaluations) { LogInfo.begin_track("Learner.learn()"); if (!params.isEmpty()) sortOnFeedback(); for (int iter = 0; iter <= numIters; iter++) { LogInfo.begin_track("Iteration %s/%s", iter, numIters); Execution.putOutput("iter", iter); Map<String, Evaluation> meanEvaluations = Maps.newHashMap(); for (String group : dataset.groups()) meanEvaluations.put(group, new Evaluation()); for (String group : dataset.groups()) { boolean lastIter = (iter == numIters); boolean updateWeights = opts.updateWeights && group.equals("train") && !lastIter; parser.onBeginDataGroup(iter, numIters, group); Evaluation eval = processExamples( iter, group, dataset.examples(group), updateWeights); MapUtils.addToList(evaluations, group, eval); meanEvaluations.get(group).add(eval); StopWatchSet.logStats(); } String path = Execution.getFile("params." + iter); if (path != null) { params.write(path); Utils.systemHard("ln -sf params." + iter + " " + Execution.getFile("params")); } LogInfo.end_track(); } LogInfo.end_track(); }
Source:
<code>PropertyValues getValues(ClassPropertyReference propertyReference, int limit, Object... filterParameters) throws XWikiRestException; <START> default PropertyValues getValue(ClassPropertyReference propertyReference, Object rawValue) <END> throws XWikiRestException { throw new UnsupportedOperationException(); }</code><technical_language>return PropertyValue (singular) method is supposed return a single value? advantage I for returning PropertyValues (plural) is avoid NPE (you return empty collection instead of null). other hand complicates code a bit need work a collection. WDYT</technical_language>

Target:
PropertyValues getValues(ClassPropertyReference propertyReference, int limit, Object... filterParameters) throws XWikiRestException; default PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { throw new UnsupportedOperationException(); }
Source:
<code>public Response getDevicesInOrganization() { List<DeviceOrganizationMetadataHolder> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getDevicesInOrganization(); if (result == null) { String msg = "No devices exist in organization"; log.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving devices in organization"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { log.error("failed to add operation", e); <START> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); <END> } }</code><technical_language>Please add message entity describing error</technical_language>

Target:
public Response getDevicesInOrganization() { List<DeviceOrganizationMetadataHolder> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getDevicesInOrganization(); if (result == null) { String msg = "No devices exist in organization"; if (log.isDebugEnabled()) { log.debug(msg); } return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving devices in organization"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { String msg = "failed to add operation"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } }
Source:
<code>private void showPostInfo(Post post) { StringBuilder text = new StringBuilder(); for (PostImage image : post.images) { text.append("Filename: ") .append(image.filename).append(".").append(image.extension) .append(" \nDimensions: ") .append(image.imageWidth).append("x").append(image.imageHeight) .append("\nSize: ") .append(AndroidUtils.getReadableFileSize(image.size, false)); if (image.spoiler) { text.append("\nSpoilered"); } text.append("\n"); } Date date = new Date () ; date.setTime((long)post.time*1000); <START> text.append(new StringBuilder("Date: " + date.toString())); <END> if (!TextUtils.isEmpty(post.id)) { text.append("\nId: ").append(post.id); } if (!TextUtils.isEmpty(post.tripcode)) { text.append("\nTripcode: ").append(post.tripcode); } if (!TextUtils.isEmpty(post.capcode)) { text.append("\nCapcode: ").append(post.capcode); } threadPresenterCallback.showPostInfo(text.toString()); }</code><technical_language>instead of creating a new StringBuilder object, do like: text.append("Date: ").append(date.toString())); (you need "\nDate: " depending line situation is)</technical_language>

Target:
private void showPostInfo(Post post) { StringBuilder text = new StringBuilder(); for (PostImage image : post.images) { text.append("Filename: ") .append(image.filename).append(".").append(image.extension) .append(" \nDimensions: ") .append(image.imageWidth).append("x").append(image.imageHeight) .append("\nSize: ") .append(AndroidUtils.getReadableFileSize(image.size, false)); if (image.spoiler) { text.append("\nSpoilered"); } text.append("\n"); } if (!TextUtils.isEmpty(post.id)) { text.append("\nId: ").append(post.id); } if (!TextUtils.isEmpty(post.tripcode)) { text.append("\nTripcode: ").append(post.tripcode); } if (!TextUtils.isEmpty(post.capcode)) { text.append("\nCapcode: ").append(post.capcode); } threadPresenterCallback.showPostInfo(text.toString()); }
Source:
<code>public final void refreshItems() { final HashSet<Integer> issuesWithNewComments = updateIssueCommentCounts(Qualifier.hasUpdatedQualifier(getCurrentFilterExpression())); listView.setCellFactory(list -> new ListPanelCell(this, panelIndex, issuesWithNewComments)); listView.saveSelection(); listView.setItems(null); listView.setItems(getElementsList()); issueCount = getElementsList().size(); closedIssueCount = getClosedIssueSize(); openIssueCount = issueCount - closedIssueCount; <START> System.out.println("closed = " + closedIssueCount + " open = " + openIssueCount); <END> listView.restoreSelection(); this.setId(guiController.getDefaultRepo() + "_col" + panelIndex); updateFooter(); }</code><technical_language>this format instead T (O + C). If Total is 0, omit part brackets</technical_language>

Target:
public final void refreshItems() { final HashSet<Integer> issuesWithNewComments = updateIssueCommentCounts(Qualifier.hasUpdatedQualifier(getCurrentFilterExpression())); listView.setCellFactory(list -> new ListPanelCell(this, panelIndex, issuesWithNewComments)); listView.saveSelection(); listView.setItems(null); listView.setItems(getElementsList()); issuesCount = getElementsList().size(); closedIssuesCount = getClosedIssuesCount(); openIssuesCount = issuesCount - closedIssuesCount; listView.restoreSelection(); this.setId(guiController.getDefaultRepo() + "_col" + panelIndex); updateFooter(); }
Source:
<code>public String <START> getDescription() <END> { if (description == null || description.isEmpty()) { } return description; }</code><technical_language>set feature transient</technical_language>

Target:
public String getDescription() { return description; }
Source:
<code><START> static ByteBuf bb(int size) { ByteBuf buf = UnpooledByteBufAllocator.DEFAULT.buffer(); for (int i = 0; i < size; i++) { <END> buf.writeByte('a'); } return buf; }</code><technical_language>bytebuf.writeZero(size);</technical_language>

Target:
static ByteBuf bb(int size) { return UnpooledByteBufAllocator.DEFAULT.buffer().writeZero(size); }
Source:
<code>String getPathsForProfile(Model model, String profileIdentifier, @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter, @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception { int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter); logger.info("BEFORE JQGRID"); HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths"); ObjectMapper objectMapper = new ObjectMapper(); <START> logger.info("BEFORE WRITER"); <END> objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class); String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" }; FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); ObjectWriter writer = objectMapper.writer(filters); return writer.writeValueAsString(jqReturn); }</code><technical_language>debug logging removed</technical_language>

Target:
String getPathsForProfile(Model model, String profileIdentifier, @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter, @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception { int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter); HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class); String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" }; FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); ObjectWriter writer = objectMapper.writer(filters); return writer.writeValueAsString(jqReturn); }
Source:
<code>public String[] getItemStrings(ITmfEvent event) { if (event instanceof TextTraceEvent) { List<TextTraceEventContent> fields = ((TextTraceEvent) event).getContent().getFields(); String[] strings = new String[fields.size()]; for (int i = 0; i < strings.length; i++) { <START> strings[i] = fields.get(i).getValue().toString(); <END> } return strings; } return EMPTY_STRING_ARRAY; }</code><technical_language>I need a null check value</technical_language>

Target:
public String[] getItemStrings(ITmfEvent event) { if (event instanceof TextTraceEvent) { List<TextTraceEventContent> fields = ((TextTraceEvent) event).getContent().getFields(); String[] strings = new String[fields.size()]; for (int i = 0; i < strings.length; i++) { Object value = fields.get(i).getValue(); strings[i] = (value == null ? EMPTY_STRING : value.toString()); } return strings; } return EMPTY_STRING_ARRAY; }
Source:
<code>public DailyJobMoon(String thingUID, AstroThingHandler handler) { <START> checkNotNull(thingUID, "Thing UID cannot be null"); <END> checkNotNull(handler, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }</code><technical_language>Please change a normal null check throw a IllegalArgumentException. This is more meaningful throwing NPE here</technical_language>

Target:
public DailyJobMoon(String thingUID, AstroThingHandler handler) { checkArgument(thingUID != null, "Thing UID cannot be null"); checkArgument(handler != null, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }
Source:
<code>public FileInStream openFile(AlluxioURI path, OpenFilePOptions options) throws IOException, AlluxioException { try { return new LocalCacheFileInStream(path, options, mDelegatedFileSystem, mFsContext.getCacheManager()); } catch (IOException e) { <START> SAMPLING_LOGGER.warn("Failed to create LocalCacheFileInStream {}", e.getMessage()); <END> return mDelegatedFileSystem.openFile(path, options); } }</code><technical_language>sampling logger? do expect a lot of openFile</technical_language>

Target:
public FileInStream openFile(AlluxioURI path, OpenFilePOptions options) throws IOException, AlluxioException { if (sCacheManager == null || !sCacheManager.isPresent()) { return mDelegatedFileSystem.openFile(path, options); } return new LocalCacheFileInStream(path, options, mDelegatedFileSystem, sCacheManager.get()); }
Source:
<code>void addTriggers(Map<String, Object> newTriggers) { triggerController.addTriggers(newTriggers); checkTriggerChanges(newTriggers); evaluateInAppMessages(); <START> } <END></code><technical_language>need call checkTriggerChanges() in removeTriggersForKeys well, a condition display trigger exists</technical_language>

Target:
void addTriggers(Map<String, Object> newTriggers) { triggerController.addTriggers(newTriggers); makeRedisplayMessagesAvailableWithTriggers(newTriggers.keySet()); evaluateInAppMessages(); }
Source:
<code>Text(TextFormat format, ImmutableList<Text> children, @Nullable ClickAction<?> clickAction, @Nullable HoverAction<?> hoverAction, @Nullable ShiftClickAction<?> shiftClickAction) { this.format = checkNotNull(format, "format"); this.children = checkNotNull(children, "children"); this.clickAction = Optional.<ClickAction<?>>ofNullable(clickAction); this.hoverAction = Optional.<HoverAction<?>>ofNullable(hoverAction); this.shiftClickAction = Optional.<ShiftClickAction<?>>ofNullable(shiftClickAction); this.childrenIterable = () -> <START> this.children.isEmpty() ? Iterators.singletonIterator(this) : new TextIterator(this); <END> }</code><technical_language>This a fix value, move field declaration (as before) java protected final Iterable<Text> childrenIterable = () -> this.children.isEmpty() ? Iterators.singletonIterator(this) : new TextIterator(this); change check for isEmpty() is set. java if (this.children.isEmpty()) { this.childrenIterable = () -> Iterators.singletonIterator(this); } else { this.childrenIterable = new TextIterator(this); }</technical_language>

Target:
Text(TextFormat format, ImmutableList<Text> children, @Nullable ClickAction<?> clickAction, @Nullable HoverAction<?> hoverAction, @Nullable ShiftClickAction<?> shiftClickAction) { this.format = checkNotNull(format, "format"); this.children = checkNotNull(children, "children"); this.clickAction = Optional.ofNullable(clickAction); this.hoverAction = Optional.ofNullable(hoverAction); this.shiftClickAction = Optional.ofNullable(shiftClickAction); this.childrenIterable = () -> new TextIterator(this); }
Source:
<code>String findRoleForPorts(Offer offer) { <START> String role = null; <END> for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals(PORT_RESOURCE_NAME)) { role = resource.getRole(); } } return role; }</code><technical_language>This return null. I wondering if setting 'null' for role affect task launch</technical_language>

Target:
String findRoleForPorts(Offer offer) { String role = MESOS_DEFAULT_ROLE; for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals(PORT_RESOURCE_NAME)) { role = resource.getRole(); } } return role; }
Source:
<code>private RenderedImage getImageFromParentCoverage(GridCoverage2D parentCoverage) { if (parentCoverage == null) { return null; } RenderedImage ri = parentCoverage.getRenderedImage(); if (ri != null) { PlanarImage pi = PlanarImage.wrapRenderedImage(ri); pi.setProperty("ParentCoverage", parentCoverage); <START> ri = pi; <END> } return ri; }</code><technical_language>This checks if ri is a planar avoids double wrapping, right</technical_language>

Target:
private RenderedImage getImageFromParentCoverage(GridCoverage2D parentCoverage) { if (parentCoverage == null) { return null; } RenderedImage ri = parentCoverage.getRenderedImage(); if (ri != null) { PlanarImage pi = PlanarImage.wrapRenderedImage(ri); pi.setProperty(PARENT_COVERAGE_PROPERTY, parentCoverage); ri = pi; } return ri; }
Source:
<code>public void adReceived(final AppLovinAd ad) { log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() ); <START> MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( this.getClass(), "" ); <END> }</code><technical_language>notifying MoPub, getAdNetworkId() instead of passing empty string callback</technical_language>

Target:
public void adReceived(final AppLovinAd ad) { log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() ); MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( this.getClass(), getAdNetworkId() ); }
Source:
<code>public String getProblemsStr() { <START> String problemsStr = ""; <END> int i = 1; for( RegisteredProject.Problem prb : problems ) { problemsStr += "["+i+"] : " + prb.message + "\n"; i++; } return problemsStr; }</code><technical_language>StringBuilder <LINK_0></technical_language>

Target:
public String getProblemsStr() { StringBuilder builder = new StringBuilder(); int i = 0; for( RegisteredProject.Problem prb : problems ) { builder.append("[").append(i++).append("] : ").append(prb.message).append("\n"); } return builder.toString(); }
Source:
<code>protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) <START> && validate(vdsValidator.validateMinimumVersionSupport(Version.v3_3)); <END> }</code><technical_language>Please FeatureSupported class for versioning checking, standard constrain feature a specific version</technical_language>

Target:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) && validate(validateMinimumVersionSupport()); }
Source:
<code>private static void setStatics(Context inContext) { currentContext = inContext; packageName = currentContext.getPackageName(); contextResources = currentContext.getResources(); PackageManager packageManager = currentContext.getPackageManager(); Intent intent = new Intent(currentContext, NotificationOpenedReceiver.class); intent.setPackage(currentContext.getPackageName()); <START> if (packageManager.queryBroadcastReceivers(intent, 0).size() > 0) <END> notificationCloseClass = NotificationOpenedReceiver.class; OneSignal.onesignalLog(OneSignal.LOG_LEVEL.DEBUG, "GenerateNotification notificationCloseClass: " + notificationCloseClass); }</code><technical_language>This runtime check in place a change in a non-major release support updated AndroidManifest.xml. safely assume NotificationDismissReceiver in 4.0.0</technical_language>

Target:
private static void setStatics(Context inContext) { currentContext = inContext; packageName = currentContext.getPackageName(); contextResources = currentContext.getResources(); }
Source:
<code>@Subscribe public void on(@NonNull PageDownloadEvent event) { int pagePosition = getPagePositionInList(event.getPage()) + 1; if (pagePosition != 0) { <START> ((PageItemView) (recyclerView.findViewHolderForAdapterPosition(pagePosition).itemView)).makeProgress(event.getProgress()); <END> } }</code><technical_language>App crashing this line. dispatch event: class org.wikipedia.events.PageDownloadEvent handler [EventHandler public void org.wikipedia.readinglist.ReadingListFragment$EventBusMethods.on(org.wikipedia.events.PageDownloadEvent)]: Attempt read field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' a null object reference</technical_language>

Target:
public void on(@NonNull PageDownloadEvent event) { int pagePosition = getPagePositionInList(event.getPage()); if (pagePosition != -1) { displayedPages.get(pagePosition).downloadProgress(event.getPage().downloadProgress()); adapter.notifyDataSetChanged(); } }
Source:
<code>public static RoboAttributeSet create(Context context, Attribute... attrs) { List<Attribute> attributesList = Lists.newArrayList(attrs); <START> return new RoboAttributeSet(attributesList, <END> shadowOf(context.getAssets()).getResourceLoader()); }</code><technical_language>constructor private</technical_language>

Target:
public static AttributeSet create(Context context, Attribute... attrs) { List<Attribute> attributesList = Lists.newArrayList(attrs); return create(context, attributesList); }
Source:
<code>public ExecutorException(Exception e) { <START> super("Continuation failed to executed due to exception raised in the Executor", e); <END> }</code><technical_language>s/executed/execute/g simplify this "An exception thrown a Executor"</technical_language>

Target:
public ExecutorException(Exception e) { super("An exception was thrown by a Executor", e); }
Source:
<code>public OutputStream getOutputStream(boolean overwrite, boolean lock) throws IOException { final FileOutputStream fileOutputStream; try { if (!isExists()) { fileOutputStream = new FileOutputStream(getLocalFile()); } else { if (overwrite) { <START> fileOutputStream = new FileOutputStream(getLocalFile()); <END> } else { fileOutputStream = new FileOutputStream(getLocalFile(), true); } } if (lock) { final FileLock fileLock; try { fileLock = fileOutputStream.getChannel().lock(); } catch (IOException ex) { fileOutputStream.close(); throw ex; } catch (Exception ex) { fileOutputStream.close(); throw new IOException(ex); } if (fileLock == null) { fileOutputStream.close(); throw new OverlappingFileLockException(); } return new OutputStream() { @Override public void write(int b) throws IOException { fileOutputStream.write(b); } @Override public void close() throws IOException { fileLock.release(); fileOutputStream.close(); } @Override public void flush() throws IOException { fileOutputStream.flush(); } @Override public void write(byte[] b) throws IOException { fileOutputStream.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { fileOutputStream.write(b, off, len); } }; } return fileOutputStream; } catch (FileNotFoundException ex) { throw ex; } }</code><technical_language>If lock is true truncated a file supposed modified new version fully written disk *and* lock released. Git relies atomic updates filesystem writing new content a new temporary file, renaming real file name new content is completely written. This method *COMPLETELY* ignores scheme, making incompatible useless for JGit</technical_language>

Target:
public OutputStream getOutputStream(boolean overwrite, boolean lock) throws IOException { final OutputStream fileOutputStream; final File outstreamFile; if (lock) { boolean newLock = !isHeldByCurrentThread(); if (!tryLock()) { throw new IOException("Could not attain lock!"); } outstreamFile = getLockFile(); if (newLock) { fileOutputStream = new GitLockOutputStream(getLocalFile(), outstreamFile, overwrite) { @Override public void close() throws IOException { super.close(); unlock(); } }; } else { fileOutputStream = new GitLockOutputStream(getLocalFile(), outstreamFile, overwrite); } } else { outstreamFile = getLocalFile(); if (!isExists()) { fileOutputStream = new FileOutputStream(outstreamFile); } else { if (overwrite) { fileOutputStream = new FileOutputStream(outstreamFile); } else { fileOutputStream = new FileOutputStream(outstreamFile, true); } } } return fileOutputStream; }
Source:
<code>public abstract InputChannel toInputChannel() throws IOException; protected void readRecoveredState(ChannelStateReader reader) throws IOException, InterruptedException { ReadResult result = ReadResult.HAS_MORE_DATA; while (result == ReadResult.HAS_MORE_DATA) { Buffer buffer = bufferManager.requestBufferBlocking(); result = internalReaderRecoveredState(reader, buffer); } <START> bufferManager.releaseFloatingBuffers(); <END> }</code><technical_language>add LOG.debug("{}/{} Finished recovering input.", inputGate.getOwningTaskName(), channelInfo);</technical_language>

Target:
public abstract InputChannel toInputChannel() throws IOException; CompletableFuture<?> getStateConsumedFuture() { return stateConsumedFuture; }
Source:
<code>public AttachSessionResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[size()]; inNet.readFully(data, 0, size()); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); fStatus = AttachReturnCode.values()[bb.getInt() - 1]; fStreamsCount = bb.getInt(); ArrayList<StreamResponse> sl = new ArrayList<>(); for (int i = 0; i < getNbStreams(); i++) { sl.add(new StreamResponse(inNet)); } <START> fStreamList = ImmutableList.copyOf(sl); <END> }</code><technical_language>no, do extra copy for nothing. ImmutableList.Builder</technical_language>

Target:
public AttachSessionResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[size()]; inNet.readFully(data, 0, size()); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); fStatus = AttachReturnCode.values()[bb.getInt() - 1]; fStreamsCount = bb.getInt(); Builder<StreamResponse> streamResponses = ImmutableList.builder(); for (int i = 0; i < getNbStreams(); i++) { streamResponses.add(new StreamResponse(inNet)); } fStreamList = streamResponses.build(); }
Source:
<code>private Handler getHandler() { <START> if (mHandler == null) { <END> mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }</code><technical_language>This thread-safe</technical_language>

Target:
private synchronized Handler getHandler() { if (mHandler == null) { mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }
Source:
<code>public void handleCreated(Event event) { Compliance compliance; ComplianceStatus status; Consumer consumer; Owner owner; ConsumerState cstate; String uuid; String ownerKey; Date eventDate; try { compliance = mapper.readValue(event.getNewEntity(), Compliance.class); consumer = compliance.getConsumer(); if (consumer == null) { throw new RuntimeException( "Unable to read consumer information from compliance status event." ); } status = compliance.getStatus(); if (status == null) { throw new RuntimeException( "Unable to read compliance status from compliance status event." ); } owner = consumer.getOwner(); if (owner == null) { throw new RuntimeException( "Unable to read owner information from compliance status event." ); } uuid = consumer.getUuid(); eventDate = status.getDate(); cstate = this.consumerStateCurator.findByUuid(uuid); if (cstate == null) { ownerKey = owner.getKey(); cstate = this.consumerStateCurator.create(new ConsumerState(uuid, ownerKey, eventDate)); } consumer.setConsumerState(cstate); <START> compliance.setDate(eventDate); <END> } catch (IOException e) { throw new RuntimeException("Could not deserialize compliance snapshot data.", e); } complianceCurator.create(compliance); }</code><technical_language>Moving _mapper.readValue(...)_ out of try/catch tidy this a little. is in throws IOException</technical_language>

Target:
public void handleCreated(Event event) { Compliance compliance; ComplianceStatus status; Consumer consumer; Owner owner; ConsumerState cstate; String uuid; String ownerKey; Date eventDate; try { compliance = mapper.readValue(event.getNewEntity(), Compliance.class); } catch (IOException e) { throw new RuntimeException("Could not deserialize compliance snapshot data.", e); } consumer = compliance.getConsumer(); if (consumer == null) { throw new RuntimeException( "Unable to read consumer information from compliance status event." ); } status = compliance.getStatus(); if (status == null) { throw new RuntimeException( "Unable to read compliance status from compliance status event." ); } owner = consumer.getOwner(); if (owner == null) { throw new RuntimeException( "Unable to read owner information from compliance status event." ); } uuid = consumer.getUuid(); eventDate = status.getDate(); cstate = this.consumerStateCurator.findByUuid(uuid); if (cstate == null) { ownerKey = owner.getKey(); cstate = this.consumerStateCurator.create(new ConsumerState(uuid, ownerKey, eventDate)); } consumer.setConsumerState(cstate); compliance.setDate(eventDate); complianceCurator.create(compliance); }
Source:
<code>public synchronized void deleteAll(List<K> keys) { <START> cache.invalidateAll(); <END> }</code><technical_language>for provided keys</technical_language>

Target:
public void deleteAll(List<K> keys) { keys.forEach(k -> delete(k)); }
Source:
<code>public static void getNextPageGroupCategoriesInCourse(String nextURL, CanvasCallback<GroupCategory[]> callback) { <START> if (APIHelpers.paramIsNull(callback, nextURL)) { <END> return; } callback.setIsNextPage(true); buildInterface(callback).getNextPageGroupCategories(nextURL, callback); }</code><technical_language>Please inline match style</technical_language>

Target:
public static void getNextPageGroupCategoriesInCourse(String nextURL, CanvasCallback<GroupCategory[]> callback) { if (APIHelpers.paramIsNull(callback, nextURL)) return; callback.setIsNextPage(true); buildInterface(callback).getNextPageGroupCategories(nextURL, callback); }