auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void register() { artifactCoordinatesValidatorRegistry.addProvider(ALIAS, this); <START> logger.info("Registered artifact coordinates validator '" + getClass().getCanonicalName() + "'" + " with alias '" + ALIAS + "'."); <END> }</code><technical_language>Please, built-in parameters logger methods. e.g.: logger.info("Nothing in db for A a : b : {}", a ,b);</technical_language>

Target:
public void register() { artifactCoordinatesValidatorRegistry.addProvider(ALIAS, this); logger.info("Registered artifact coordinates validator '{}' with alias '{}'.", getClass().getCanonicalName(), ALIAS); }
Source:
<code>@Override protected void body() throws InterruptedException, IgniteInterruptedCheckedException { while (!isCancelled() && !Thread.interrupted()) { blockingSectionBegin(); try { synchronized (this) { while (readyForFlushSize.get() < flushBatchSize && !isCancelled()) wait(); } <START> flushBuffer(); <END> } finally { blockingSectionEnd(); } } fileWriter = null; ringByteBuffer.close(); ringByteBuffer.poll(); ringByteBuffer.free(); U.closeQuiet(fileIo); stringIds.clear(); stopFut.onDone(); log.info("Performance statistics writer stopped."); }</code><technical_language>flushBuffer is in blocking section</technical_language>

Target:
@Override protected void body() throws InterruptedException, IgniteInterruptedCheckedException { try { long writtenToFile = 0; while (!isCancelled()) { blockingSectionBegin(); try { synchronized (this) { if (writtenToFile / flushSize == writtenToBuf.get() / flushSize) wait(); } } finally { blockingSectionEnd(); } writtenToFile += flush(); } flush(); } catch (InterruptedException e) { try { flush(); } catch (IOException ignored) { } } catch (ClosedByInterruptException ignored) { } catch (IOException e) { log.error("Unable to write to the performance statistics file.", e); } }
Source:
<code>public void open() throws IOException { writer = CompressionFactory.getLongSerializer( <START> ioPeon, String.format("%s_little", metricName), IndexIO.BYTE_ORDER, CompressionFactory.DEFAULT_LONG_ENCODING, <END> CompressedObjectStrategy.DEFAULT_COMPRESSION_STRATEGY ); writer.open(); }</code><technical_language>this user-specified long encoding instead of default</technical_language>

Target:
public void open() throws IOException { writer = CompressionFactory.getLongSerializer( ioPeon, String.format("%s_little", metricName), IndexIO.BYTE_ORDER, encoding, compression ); writer.open(); }
Source:
<code>private void testUpdateInterface(Guid interface_id) { VdsNetworkInterface iface = dao.get(interface_id); iface.setName(iface.getName().toUpperCase()); iface.setQos(newQos); dao.updateInterfaceForVds(iface); VdsNetworkInterface ifaced = dao.get(interface_id); <START> assertTrue(ifaced.getName().equals(iface.getName()) && ifaced.getQos().equals(iface.getQos())); <END> }</code><technical_language>I a couple of assert equals give output in case of failure. (Remember expected one)</technical_language>

Target:
private void testUpdateInterface(Guid interface_id) { VdsNetworkInterface iface = dao.get(interface_id); iface.setName(iface.getName().toUpperCase()); iface.setQos(newQos); dao.updateInterfaceForVds(iface); VdsNetworkInterface ifaced = dao.get(interface_id); assertEquals(iface.getName(), ifaced.getName()); assertEquals(iface.getQos(), ifaced.getQos()); }
Source:
<code>public static void setConnectorInfo(JobConf job, String principal, AuthenticationToken token) throws AccumuloSecurityException { if (token instanceof KerberosToken) { log.info("Received KerberosToken, attempting to fetch DelegationToken"); try { Connector conn = Connector.builder().usingClientInfo(getClientInfo(job)) <START> .usingToken(principal, token).build(); <END> token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig()); } catch (Exception e) { log.warn("Failed to automatically obtain DelegationToken, " + "Mappers/Reducers will likely fail to communicate with Accumulo", e); } } if (token instanceof DelegationTokenImpl) { DelegationTokenImpl delegationToken = (DelegationTokenImpl) token; AuthenticationTokenIdentifier identifier = delegationToken.getIdentifier(); Token<AuthenticationTokenIdentifier> hadoopToken = new Token<>(identifier.getBytes(), delegationToken.getPassword(), identifier.getKind(), delegationToken.getServiceName()); job.getCredentials().addToken(hadoopToken.getService(), hadoopToken); } OutputConfigurator.setConnectorInfo(CLASS, job, principal, token); }</code><technical_language>I this behavior is needed. reason expect keytab *won't* worker nodes. If user wants a delegation token, create pass in. This auto-allocation of delegation tokens user explicit acknowledgement is a bit dangerous users intend. If getClientInfo added solely support this feature, is needed</technical_language>

Target:
public static void setConnectorInfo(JobConf job, String principal, AuthenticationToken token) throws AccumuloSecurityException { if (token instanceof DelegationTokenImpl) { DelegationTokenImpl delegationToken = (DelegationTokenImpl) token; AuthenticationTokenIdentifier identifier = delegationToken.getIdentifier(); Token<AuthenticationTokenIdentifier> hadoopToken = new Token<>(identifier.getBytes(), delegationToken.getPassword(), identifier.getKind(), delegationToken.getServiceName()); job.getCredentials().addToken(hadoopToken.getService(), hadoopToken); } OutputConfigurator.setConnectorInfo(CLASS, job, principal, token); }
Source:
<code>private void update() { if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { <START> LOG.warn("Failed to notify error observer"); <END> } } finally { busy.set(false); } } }</code><technical_language>this pass exception logger user failure was</technical_language>

Target:
private void update() { if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer", e2); } } finally { busy.set(false); } } }
Source:
<code>private synchronized <T> EventListenerGroupImpl<T> getOrCreateEventListenerGroup(EventType<T> eventType) { final int sizeOriginal = this.registeredEventListeners.length; if ( eventType.ordinal() < sizeOriginal ) { final EventListenerGroupImpl registeredEventListener = registeredEventListeners[ eventType.ordinal() ]; if ( registeredEventListener != null ) { return registeredEventListener; } } else { final int sizeNew = EventType.values().size(); final EventListenerGroupImpl[] registeredEventListenersNew = new EventListenerGroupImpl[sizeNew]; System.arraycopy( this.registeredEventListeners, 0, registeredEventListenersNew, 0, sizeOriginal ); this.registeredEventListeners = registeredEventListenersNew; } final EventListenerGroupImpl listenerGroup = new EventListenerGroupImpl( eventType, EventListenerRegistryImpl.this ); registeredEventListeners[eventType.ordinal()] = listenerGroup; return listenerGroup; <START> } <END></code><technical_language>I original reason array list is for performance tuning; for reason consider limiting synchronizing scope possible. If I mistaken, listener is appended, need include code if block synchronization block; furthermore, shrink synchronization scope else block above, some double checked locking paradigm. I 100% need volatile keyword for registeredEventListeners. thread's array expanding invisible other thread JDK's memory model</technical_language>

Target:
private synchronized <T> EventListenerGroupImpl<T> getOrCreateEventListenerGroup(EventType<T> eventType) { final int sizeOriginal = this.registeredEventListeners.length; final EventListenerGroupImpl[] registeredEventListenersNew; if ( eventType.ordinal() < sizeOriginal ) { final EventListenerGroupImpl registeredEventListener = registeredEventListeners[ eventType.ordinal() ]; if ( registeredEventListener != null ) { return registeredEventListener; } registeredEventListenersNew = this.registeredEventListeners; } else { final int sizeNew = Math.max( eventType.ordinal() + 1, EventType.values().size() ); registeredEventListenersNew = new EventListenerGroupImpl[sizeNew]; System.arraycopy( this.registeredEventListeners, 0, registeredEventListenersNew, 0, sizeOriginal ); } final EventListenerGroupImpl listenerGroup = new EventListenerGroupImpl( eventType, EventListenerRegistryImpl.this ); registeredEventListenersNew[eventType.ordinal()] = listenerGroup; this.registeredEventListeners = registeredEventListenersNew; return listenerGroup; }
Source:
<code><START> default CompletableFuture<String> getsAsync(String row, Column column) { <END> return CompletableFuture.supplyAsync(() -> gets(row, column)); }</code><technical_language>need Bytes getAsync(Bytes row, Column column) Bytes getAsync(Bytes row, Column column) methods also. string methods call bytes methods</technical_language>

Target:
default CompletableFuture<String> getsAsync(String row, Column column) { return CompletableFuture.completedFuture(gets(row, column)); }
Source:
<code>public void putMetrics(MetricsRecord metricsRecord) { for (AbstractMetric metrics : metricsRecord.metrics()) { if (metrics.type() == MetricType.COUNTER || metrics.type() == MetricType.GAUGE) { String key = prometheusName( metricsRecord.name(), metrics.name()); StringBuilder builder = new StringBuilder(); builder.append("# TYPE ") .append(key) .append(" ") .append(metrics.type().toString().toLowerCase()) .append("\n"); StringBuilder prometheusMetricKey = new StringBuilder(); prometheusMetricKey.append(key) .append("{"); String sep = ""; for (MetricsTag tag : metricsRecord.tags()) { String tagName = tag.name().toLowerCase(); if (!tagName.equals("numopenconnectionsperuser")) { prometheusMetricKey.append(sep) .append(tagName) .append("=\"") .append(tag.value()) .append("\""); sep = ","; } } prometheusMetricKey.append("}"); <START> builder.append(prometheusMetricKey.toString()); <END> builder.append(" "); builder.append(metrics.value()); builder.append("\n"); metricLines.put(prometheusMetricKey.toString(), builder.toString()); } } }</code><technical_language>worth storing prometheusMetricKey.toString() in a local variable</technical_language>

Target:
public void putMetrics(MetricsRecord metricsRecord) { for (AbstractMetric metrics : metricsRecord.metrics()) { if (metrics.type() == MetricType.COUNTER || metrics.type() == MetricType.GAUGE) { String key = prometheusName( metricsRecord.name(), metrics.name()); StringBuilder builder = new StringBuilder(); builder.append("# TYPE ") .append(key) .append(" ") .append(metrics.type().toString().toLowerCase()) .append("\n"); StringBuilder prometheusMetricKey = new StringBuilder(); prometheusMetricKey.append(key) .append("{"); String sep = ""; for (MetricsTag tag : metricsRecord.tags()) { String tagName = tag.name().toLowerCase(); if (!tagName.equals("numopenconnectionsperuser")) { prometheusMetricKey.append(sep) .append(tagName) .append("=\"") .append(tag.value()) .append("\""); sep = ","; } } prometheusMetricKey.append("}"); String prometheusMetricKeyAsString = prometheusMetricKey.toString(); builder.append(prometheusMetricKeyAsString); builder.append(" "); builder.append(metrics.value()); builder.append("\n"); metricLines.put(prometheusMetricKeyAsString, builder.toString()); } } }
Source:
<code>private int waitForCompletion(int commandId, long timeout) throws IOException, InterruptedException { URL url = new URL("<LINK_0>" + commandId); long endTime = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < endTime) { Map response = makeRequest(url, null); if (response.get("status").equals("done")) { return 0; } System.out.println("waiting 3 seconds for results of query " + commandId + ". Current status " + response.get("status")); Thread.sleep(3000); } <START> return 1; END> }</code><technical_language>1 return error throw IOException in this case</technical_language>

Target:
private void waitForCompletion(int commandId, long timeout) throws IOException, InterruptedException { URL url = new URL("<LINK_0>" + commandId); long endTime = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < endTime) { Map response = makeRequest(url, null); if (response.get("status").equals("done")) { return; } System.out.println("waiting 3 seconds for results of query " + commandId + ". Current status " + response.get("status")); Thread.sleep(3000); } throw new IOException("Qubole commandId" + commandId + " failed to return within timeout."); }
Source:
<code><START> private MethodBehavior createIsEmptyOrBlankMethodBehavior(Symbol.MethodSymbol symbol, Constraint constraint) { <END> MethodBehavior behavior; behavior = new MethodBehavior(symbol); HappyPathYield nullYield = new HappyPathYield(behavior); nullYield.parametersConstraints.add(pmapForConstraint(ObjectConstraint.NULL)); nullYield.setResult(-1, pmapForConstraint(constraint)); behavior.addYield(nullYield); MethodYield notNullYield = new HappyPathYield(behavior); notNullYield.parametersConstraints.add(pmapForConstraint(ObjectConstraint.NOT_NULL)); behavior.addYield(notNullYield); behavior.completed(); return behavior; }</code><technical_language>static pmapForConstraint static</technical_language>

Target:
private static MethodBehavior createIsEmptyOrBlankMethodBehavior(Symbol.MethodSymbol symbol, Constraint constraint) { MethodBehavior behavior = new MethodBehavior(symbol); HappyPathYield nullYield = new HappyPathYield(behavior); nullYield.parametersConstraints.add(pmapForConstraint(ObjectConstraint.NULL)); nullYield.setResult(-1, pmapForConstraint(constraint)); behavior.addYield(nullYield); MethodYield notNullYield = new HappyPathYield(behavior); notNullYield.parametersConstraints.add(pmapForConstraint(ObjectConstraint.NOT_NULL)); behavior.addYield(notNullYield); behavior.completed(); return behavior; }
Source:
<code>public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result = Collections.emptyList(); <START> Block parent = context.getCurrentMacroBlock().getParent().getParent(); <END> if (parent != null && parent instanceof FigureBlock) { XDOM xdom = this.contentParser.parse(content, context, false, false); List<Block> figureCaptionChildren = xdom.getChildren(); this.parserUtils.removeTopLevelParagraph(figureCaptionChildren); result = Collections.singletonList(new FigureCaptionBlock(Collections.singletonList( new UnchangedContentBlock(figureCaptionChildren) ))); } return result; }</code><technical_language>fragile a bit weird, no? parent grandparent (cf variable name) ;)</technical_language>

Target:
public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result = Collections.emptyList(); Block parent = context.getCurrentMacroBlock().getParent(); if (parent != null && parent instanceof FigureBlock) { XDOM xdom = this.contentParser.parse(content, context, false, false); List<Block> figureCaptionChildren = xdom.getChildren(); this.parserUtils.removeTopLevelParagraph(figureCaptionChildren); result = Collections.singletonList(new FigureCaptionBlock(figureCaptionChildren)); } return result; }
Source:
<code>public final void setExcludedPackages(String... excludedPackages) { this.excludedPackages = Collections.unmodifiableSet(Arrays.stream(excludedPackages) <START> .map(x -> x + DOT).collect(Collectors.toSet())); <END> }</code><technical_language>append DOT if users accidentally appended it? care</technical_language>

Target:
public final void setExcludedPackages(String... excludedPackages) { final List<String> invalidIdentifiers = Arrays.stream(excludedPackages) .filter(x -> !CommonUtils.isName(x)) .collect(Collectors.toList()); if (!invalidIdentifiers.isEmpty()) { throw new IllegalArgumentException( "the following values are not valid identifiers: " + invalidIdentifiers.stream().collect(Collectors.joining(", ", "[", "]"))); } this.excludedPackages = Collections.unmodifiableSet( Arrays.stream(excludedPackages).collect(Collectors.toSet())); }
Source:
<code>public int executeTask(HiveHistory hiveHistory) { try { this.setStarted(); if (hiveHistory != null) { hiveHistory.logPlanProgress(queryPlan); } String queryId = conf.getVar(HIVEQUERYID); if (!org.apache.commons.lang.StringUtils.isEmpty(queryId)) { <START> conf.set(MRJobConfig.JOB_TAGS, queryId); <END> } int retval = execute(driverContext); this.setDone(); if (hiveHistory != null) { hiveHistory.logPlanProgress(queryPlan); } return retval; } catch (IOException e) { throw new RuntimeException("Unexpected error: " + e.getMessage(), e); } }</code><technical_language>is check if set append tag</technical_language>

Target:
public int executeTask(HiveHistory hiveHistory) { try { this.setStarted(); if (hiveHistory != null) { hiveHistory.logPlanProgress(queryPlan); } if (conf != null) { LOG.debug("Task getting executed using mapred tag : " + conf.get(MRJobConfig.JOB_TAGS)); } int retval = execute(driverContext); this.setDone(); if (hiveHistory != null) { hiveHistory.logPlanProgress(queryPlan); } return retval; } catch (IOException e) { throw new RuntimeException("Unexpected error: " + e.getMessage(), e); } }
Source:
<code>public String getQuestionResultStatisticsHtml( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if (view.equals("student") || responses.isEmpty()) { return ""; } String html = ""; StringBuilder fragments = new StringBuilder(100); Map<String, List<Integer>> optionRanks = generateOptionRanksMapping(responses); DecimalFormat df = new DecimalFormat("#.##"); for (Entry<String, List<Integer>> entry : optionRanks.entrySet()) { List<Integer> ranks = entry.getValue(); double average = computeAverage(ranks); String ranksReceived = getListOfRanksReceivedAsString(ranks); String option = entry.getKey(); fragments.append(FeedbackQuestionFormTemplates.populateTemplate(FeedbackQuestionFormTemplates.RANK_RESULT_STATS_OPTIONFRAGMENT, "${rankOptionValue}", Sanitizer.sanitizeForHtml(option), "${ranksReceived}", ranksReceived, "${averageRank}", df.format(average))); } html = FeedbackQuestionFormTemplates.populateTemplate(FeedbackQuestionFormTemplates.RANK_RESULT_OPTION_STATS, "${optionRecipientDisplayName}", "Option", "${fragments}", fragments.toString()); <START> return html; <END> }</code><technical_language>Similar issue html variable here</technical_language>

Target:
public String getQuestionResultStatisticsHtml( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if ("student".equals(view) || responses.isEmpty()) { return ""; } StringBuilder fragments = new StringBuilder(100); Map<String, List<Integer>> optionRanks = generateOptionRanksMapping(responses); DecimalFormat df = new DecimalFormat("#.##"); for (Entry<String, List<Integer>> entry : optionRanks.entrySet()) { List<Integer> ranks = entry.getValue(); double average = computeAverage(ranks); String ranksReceived = getListOfRanksReceivedAsString(ranks); String option = entry.getKey(); fragments.append(FeedbackQuestionFormTemplates.populateTemplate(FeedbackQuestionFormTemplates.RANK_RESULT_STATS_OPTIONFRAGMENT, "${rankOptionValue}", Sanitizer.sanitizeForHtml(option), "${ranksReceived}", ranksReceived, "${averageRank}", df.format(average))); } return FeedbackQuestionFormTemplates.populateTemplate(FeedbackQuestionFormTemplates.RANK_RESULT_OPTION_STATS, "${optionRecipientDisplayName}", "Option", "${fragments}", fragments.toString()); }
Source:
<code>public void resetTheApp() { resetApp(); appWasReset(); try { <START> Thread.sleep(10000); <END> } catch (Throwable t) }</code><technical_language>do need this sleep</technical_language>

Target:
public void resetTheApp() { resetApp(); appWasReset(); }
Source:
<code>public ImportVmCommand(ImportVmParameters parameters) { super(parameters); setVmId(parameters.getContainerId()); parameters.setEntityId(getVmId()); setVm(parameters.getVm()); parameters.setEntityId(getVm().getId()); setVdsGroupId(parameters.getVdsGroupId()); <START> imageList = new ArrayList<DiskImage>(getVm().getDiskMap().values()); <END> ensureDomainMap(); }</code><technical_language>get NPE ? parameters null VM value, do action is performed command is initialized is sort of validation prevent client sending null for VM. In this case - getVm().getDiskMap() end NPE</technical_language>

Target:
public ImportVmCommand(ImportVmParameters parameters) { super(parameters); setVmId(parameters.getContainerId()); parameters.setEntityId(getVmId()); setVm(parameters.getVm()); parameters.setEntityId(getVm().getId()); setVdsGroupId(parameters.getVdsGroupId()); if (parameters.getVm() != null && getVm().getDiskMap() != null) { imageList = new ArrayList<DiskImage>(getVm().getDiskMap().values()); } ensureDomainMap(imageList, getParameters().getDestDomainId()); }
Source:
<code>public boolean test(Object object) { <START> boolean b = false; <END> for (Class<?> immutableClass : this.unmodifiableClasses) { if (immutableClass.isInstance(object)) { b = true; break; } } if (b) { if (object instanceof Set) return true; Collection<?> collection = (object instanceof Map) ? ((Map<?, ?>) object).values() : (Collection<?>) object; for (Object e : collection) { if (! this.elementImmutability.test(e)) { return false; } } return true; } return false; }</code><technical_language>variable name, e.g. "unmodifiable"</technical_language>

Target:
public boolean test(Object object) { for (Class<?> immutableClass : unmodifiableClasses) { if (immutableClass.isInstance(object)) { if (object instanceof Set) return true; Collection<?> collection = (object instanceof Map) ? ((Map<?, ?>) object).values() : (Collection<?>) object; for (Object e : collection) { if (! this.elementImmutability.test(e)) { return false; } } return true; } } return false; }
Source:
<code>public void testEmptyMapCP() throws Exception { SMRMap<String, String> map = r.getObjectsView().build() .setType(SMRMap.class) .setStreamName("Map1") .open(); MultiCheckpointWriter mcw = new MultiCheckpointWriter(); mcw.addMap(map); long address = mcw.appendCheckpoints(r, "A1").getSequence(); <START> assertThat(address).isEqualTo(0); <END> IStreamView sv = r.getStreamsView().get(CorfuRuntime.getStreamID("S1")); final int objSize = 100; long a1 = sv.append(new byte[objSize]); final long cpEndAddress = 3L; assertThat(a1).isEqualTo(cpEndAddress); }</code><technical_language>0 means? If presented in Address class, please Adress.SOME_CONSTANT for</technical_language>

Target:
public void testEmptyMapCP() throws Exception { SMRMap<String, String> map = r.getObjectsView().build() .setType(SMRMap.class) .setStreamName("Map1") .open(); MultiCheckpointWriter mcw = new MultiCheckpointWriter(); mcw.addMap(map); long address = mcw.appendCheckpoints(r, "A1").getSequence(); assertThat(address).isEqualTo(-1); IStreamView sv = r.getStreamsView().get(CorfuRuntime.getStreamID("S1")); final int objSize = 100; long a1 = sv.append(new byte[objSize]); final long cpEndAddress = 0L; assertThat(a1).isEqualTo(cpEndAddress); }
Source:
<code>protected EmailTemplate processTemplate(String subjectKey, List<Object> subjectAttributes, String template, Map<String, Object> attributes) throws EmailException { try { Theme theme = getTheme(); Locale locale = session.getContext().resolveLocale(user); attributes.put("locale", locale); Properties rb = theme.getMessages(locale); attributes.put("msg", new MessageFormatterMethod(locale, rb)); attributes.put("properties", theme.getProperties()); String subject = new MessageFormat(rb.getProperty(subjectKey, subjectKey), locale).format(subjectAttributes.toArray()); String textTemplate = String.format("text/%s", template); String textBody; try { textBody = freeMarker.processTemplate(attributes, textTemplate, theme); } catch (final FreeMarkerException e) { textBody = null; <START> logger.warn("Failed to template plain text email.", e); <END> } String htmlTemplate = String.format("html/%s", template); String htmlBody; try { htmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme); } catch (final FreeMarkerException e) { htmlBody = null; logger.warn("Failed to template html email.", e); } if (textBody == null && htmlBody == null) { throw new EmailException("Both plain text and html are empty!"); } return new EmailTemplate(subject, textBody, htmlBody); } catch (Exception e) { throw new EmailException("Failed to template email", e); } }</code><technical_language>this do: throw new EmailException("Failed template plain text email.", e);</technical_language>

Target:
protected EmailTemplate processTemplate(String subjectKey, List<Object> subjectAttributes, String template, Map<String, Object> attributes) throws EmailException { try { Theme theme = getTheme(); Locale locale = session.getContext().resolveLocale(user); attributes.put("locale", locale); Properties rb = theme.getMessages(locale); attributes.put("msg", new MessageFormatterMethod(locale, rb)); attributes.put("properties", theme.getProperties()); String subject = new MessageFormat(rb.getProperty(subjectKey, subjectKey), locale).format(subjectAttributes.toArray()); String textTemplate = String.format("text/%s", template); String textBody; try { textBody = freeMarker.processTemplate(attributes, textTemplate, theme); } catch (final FreeMarkerException e) { throw new EmailException("Failed to template plain text email.", e); } String htmlTemplate = String.format("html/%s", template); String htmlBody; try { htmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme); } catch (final FreeMarkerException e) { throw new EmailException("Failed to template html email.", e); } return new EmailTemplate(subject, textBody, htmlBody); } catch (Exception e) { throw new EmailException("Failed to template email", e); } }
Source:
<code>public void prepare() throws IOException { e = SQLExecutor.builder(clusterService) <START> .enableDefaultTables() <END> .addTable("create table t (" + " id integer primary key," + " qty integer constraint check_qty_gt_zero check (qty > 0)," + " constraint check_id_ge_zero check (id >= 0)" + ")") .build(); plannerContext = e.getPlannerContext(clusterService.state()); }</code><technical_language>suggestion Please add tables used. Wastes CPU cycles</technical_language>

Target:
public void prepare() throws IOException { e = SQLExecutor.builder(clusterService) .addTable("create table t (" + " id integer primary key," + " qty integer constraint check_qty_gt_zero check (qty > 0)," + " constraint check_id_ge_zero check (id >= 0)" + ")") .build(); plannerContext = e.getPlannerContext(clusterService.state()); }
Source:
<code>public static void main( String[] args ) throws Exception { WebSocketImpl.DEBUG = true; ChatServer chatserver = new ChatServer( 8887 ); String STORETYPE = "JKS"; <START> String KEYSTORE = "D:\\GitHub\\Java-WebSocket\\src\\main\\example\\keystore.jks"; <END> String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance( STORETYPE ); File kf = new File( KEYSTORE ); ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() ); KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); kmf.init( ks, KEYPASSWORD.toCharArray() ); TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); tmf.init( ks ); SSLContext sslContext = null; sslContext = SSLContext.getInstance( "TLS" ); sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); chatserver.setWebSocketFactory( new DefaultSSLWebSocketServerFactory( sslContext ) ); chatserver.start(); }</code><technical_language>please revert this change</technical_language>

Target:
public static void main( String[] args ) throws Exception { WebSocketImpl.DEBUG = true; ChatServer chatserver = new ChatServer( 8887 ); String STORETYPE = "JKS"; String KEYSTORE = "keystore.jks"; String STOREPASSWORD = "storepassword"; String KEYPASSWORD = "keypassword"; KeyStore ks = KeyStore.getInstance( STORETYPE ); File kf = new File( KEYSTORE ); ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() ); KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); kmf.init( ks, KEYPASSWORD.toCharArray() ); TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); tmf.init( ks ); SSLContext sslContext = null; sslContext = SSLContext.getInstance( "TLS" ); sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); chatserver.setWebSocketFactory( new DefaultSSLWebSocketServerFactory( sslContext ) ); chatserver.start(); }
Source:
<code>private void collectErrorMessages(ValidationException e, StringBuilder builder) { builder.append(e.getMessage()); if (!e.getCausingExceptions().isEmpty()) { e.getCausingExceptions().stream() .forEach(causingException -> { <START> builder.append("\n"); <END> collectErrorMessages(causingException, builder); }); } }</code><technical_language>mutating lambdas</technical_language>

Target:
private void collectErrorMessages(ValidationException e, StringBuilder builder) { builder.append(e.getMessage()); e.getCausingExceptions().stream() .forEach(causingException -> { builder.append("\n"); collectErrorMessages(causingException, builder); }); }
Source:
<code>static String computeKeyHash(String prefix, String namespace, byte[] key) { <START> return prefix + ':' + DigestUtils.sha1Hex(namespace) + ':' + DigestUtils.sha1Hex(key); <END> }</code><technical_language>String.format</technical_language>

Target:
static String computeKeyHash(String prefix, String namespace, byte[] key) { return String.format("%s:%s:%s", prefix, DigestUtils.sha1Hex(namespace), DigestUtils.sha1Hex(key)); }
Source:
<code>public static List<AssociationOrderBy> parse(String fragment, SessionFactoryImplementor factory, ColumnMapper columnMapper) { TranslationContext context = new TranslationContext() { public SessionFactoryImplementor getSessionFactory() { return factory; } public Dialect getDialect() { return factory.getServiceRegistry().getService( JdbcServices.class ).getDialect(); } public SQLFunctionRegistry getSqlFunctionRegistry() { return factory.getSqlFunctionRegistry(); } public ColumnMapper getColumnMapper() { return columnMapper; } }; GeneratedOrderByLexer lexer = new GeneratedOrderByLexer( new StringReader( fragment ) ); OrderByFragmentParser parser = new OrderByFragmentParser( lexer, context ); try { parser.orderByFragment(); } catch ( HibernateException e ) { throw e; } catch ( Throwable t ) { <START> throw new HibernateException( "Unable to parse order-by fragment", t ); <END> } OGMOrderByRendered rendered = new OGMOrderByRendered(); try { rendered.orderByFragment( parser.getAST() ); return rendered.getOrderByItems(); } catch (RecognitionException e) { throw new HibernateException( "Unable to render order-by fragment", e ); } }</code><technical_language>this in log interface</technical_language>

Target:
public static List<AssociationOrderBy> parse(String fragment, SessionFactoryImplementor factory, ColumnMapper columnMapper) { TranslationContext context = new TranslationContext() { public SessionFactoryImplementor getSessionFactory() { return factory; } public Dialect getDialect() { return factory.getServiceRegistry().getService( JdbcServices.class ).getDialect(); } public SQLFunctionRegistry getSqlFunctionRegistry() { return factory.getSqlFunctionRegistry(); } public ColumnMapper getColumnMapper() { return columnMapper; } }; GeneratedOrderByLexer lexer = new GeneratedOrderByLexer( new StringReader( fragment ) ); OrderByFragmentParser parser = new OrderByFragmentParser( lexer, context ); try { parser.orderByFragment(); } catch ( HibernateException e ) { throw e; } catch ( Throwable t ) { throw log.unableToParseOrderByFragment( fragment, t ); } OGMOrderByRendered rendered = new OGMOrderByRendered(); try { rendered.orderByFragment( parser.getAST() ); return rendered.getOrderByItems(); } catch (RecognitionException e) { throw log.unableToRenderOrderByFragment( fragment, e ); } }
Source:
<code><START> public AuthenticateRequest(@Provider Supplier<Credentials> splr) { <END> authToken = splr.get(); }</code><technical_language>Remove public modifier. Injection constructors package private</technical_language>

Target:
AuthenticateRequest(@Provider Supplier<Credentials> splr) { authToken = splr.get(); checkNotNull(authToken.identity, "credential returned null"); }
Source:
<code>private void verifyCacheHeaders(boolean cacheable, MockRestResponseChannel restResponseChannel) { if (cacheable) { Assert.assertTrue("Expires value should be in the future", RestUtils.getTimeFromDateString(restResponseChannel.getHeader(RestUtils.Headers.EXPIRES)) > System.currentTimeMillis()); Assert.assertEquals("Cache-Control value not as expected", "max-age=" + FRONTEND_CONFIG.frontendCacheValiditySeconds, restResponseChannel.getHeader(RestUtils.Headers.CACHE_CONTROL)); Assert.assertNull("Pragma value should not have been set", restResponseChannel.getHeader(RestUtils.Headers.PRAGMA)); } else { <START> Assert.assertEquals("Expires value is incorrect for private blob", <END> restResponseChannel.getHeader(RestUtils.Headers.DATE), restResponseChannel.getHeader(RestUtils.Headers.EXPIRES)); Assert.assertEquals("Cache-Control value not as expected", "private, no-cache, no-store, proxy-revalidate", restResponseChannel.getHeader(RestUtils.Headers.CACHE_CONTROL)); Assert.assertEquals("Pragma value not as expected", "no-cache", restResponseChannel.getHeader(RestUtils.Headers.PRAGMA)); } }</code><technical_language>minor: fix log statement. "incorrect for non-cachable blob"</technical_language>

Target:
private void verifyCacheHeaders(boolean cacheable, MockRestResponseChannel restResponseChannel) { if (cacheable) { Assert.assertTrue("Expires value should be in the future", RestUtils.getTimeFromDateString(restResponseChannel.getHeader(RestUtils.Headers.EXPIRES)) > System.currentTimeMillis()); Assert.assertEquals("Cache-Control value not as expected", "max-age=" + FRONTEND_CONFIG.frontendCacheValiditySeconds, restResponseChannel.getHeader(RestUtils.Headers.CACHE_CONTROL)); Assert.assertNull("Pragma value should not have been set", restResponseChannel.getHeader(RestUtils.Headers.PRAGMA)); } else { Assert.assertEquals("Expires value is incorrect for non-cacheable blob", restResponseChannel.getHeader(RestUtils.Headers.DATE), restResponseChannel.getHeader(RestUtils.Headers.EXPIRES)); Assert.assertEquals("Cache-Control value not as expected", "private, no-cache, no-store, proxy-revalidate", restResponseChannel.getHeader(RestUtils.Headers.CACHE_CONTROL)); Assert.assertEquals("Pragma value not as expected", "no-cache", restResponseChannel.getHeader(RestUtils.Headers.PRAGMA)); } }
Source:
<code><START> private void assertEquivalentAssignment(final Map<String, List<TaskId>> thisAssignment, <END> final Map<String, List<TaskId>> otherAssignment) { for (final Map.Entry<String, List<TaskId>> entry : thisAssignment.entrySet()) { final String consumer = entry.getKey(); assertTrue(otherAssignment.containsKey(consumer)); final List<TaskId> thisTaskList = entry.getValue(); final List<TaskId> otherTaskList = otherAssignment.get(consumer); assertEquals(thisTaskList.size(), otherTaskList.size()); assertThat(new HashSet<>(thisTaskList), equalTo(new HashSet<>(otherTaskList))); } }</code><technical_language>rely equals function of map list here? I checks for "exact equality", while otherAssignment a super-set of thisAssignment pass</technical_language>

Target:
private void assertEquivalentAssignment(final Map<String, List<TaskId>> thisAssignment, final Map<String, List<TaskId>> otherAssignment) { assertEquals(thisAssignment.size(), otherAssignment.size()); for (final Map.Entry<String, List<TaskId>> entry : thisAssignment.entrySet()) { final String consumer = entry.getKey(); assertTrue(otherAssignment.containsKey(consumer)); final List<TaskId> thisTaskList = entry.getValue(); Collections.sort(thisTaskList); final List<TaskId> otherTaskList = otherAssignment.get(consumer); Collections.sort(otherTaskList); assertThat(thisTaskList, equalTo(otherTaskList)); } }
Source:
<code>public Expression create(ExpressionConverter converter, IConfigurationElement element) { String name = element.getName(); <START> if (name==null) <END> return null; switch (name) { case HasFileExpression.TAG: return new HasFileExpression(element); case HasFileRecursivelyExpression.TAG: return new HasFileRecursivelyExpression(element); case HasFileWithSuffixRecursivelyExpression.TAG: return new HasFileWithSuffixRecursivelyExpression(element); case HasFolderExpression.TAG: return new HasFolderExpression(element); default: break; } return null; }</code><technical_language>{} for blocks</technical_language>

Target:
public Expression create(ExpressionConverter converter, IConfigurationElement element) { String name = element.getName(); if (name == null) { return null; } switch (name) { case HasFileExpression.TAG: return new HasFileExpression(element); case HasFileRecursivelyExpression.TAG: return new HasFileRecursivelyExpression(element); case HasFileWithSuffixRecursivelyExpression.TAG: return new HasFileWithSuffixRecursivelyExpression(element); case HasFolderExpression.TAG: return new HasFolderExpression(element); default: break; } return null; }
Source:
<code><START> public List<ProgramState> setConstraint(ProgramState initialProgramState, BooleanConstraint booleanConstraint) { <END> ProgramState programState = initialProgramState; if (leftOp.equals(rightOp)) { if (shouldNotInverse().equals(booleanConstraint)) { return ImmutableList.of(programState); } return ImmutableList.of(); } if (leftOp.id > 2 && rightOp.id > 2) { SymbolicValueRelation relationToFullfill = getSymbolicValueRelation(); if (relationToFullfill != null) { if (BooleanConstraint.FALSE.equals(booleanConstraint)) { relationToFullfill = relationToFullfill.inverse(); } Boolean fullFilled = programState.checkValidity(relationToFullfill); if (fullFilled == null) { programState = programState.addBinaryConstraint(relationToFullfill); } else if (!fullFilled.booleanValue()) { return ImmutableList.of(); } } } List<ProgramState> copiedConstraints = copyConstraint(leftOp, rightOp, programState, booleanConstraint); if (copiedConstraints.isEmpty()) { return ImmutableList.of(); } List<ProgramState> results = new ArrayList<>(); for (ProgramState ps : copiedConstraints) { List<ProgramState> copiedConstraintsRightToLeft = copyConstraint(rightOp, leftOp, ps, booleanConstraint); if (copiedConstraintsRightToLeft.size() == 1 && copiedConstraintsRightToLeft.get(0).equals(programState)) { results.add(programState.addConstraint(this, booleanConstraint)); } else { results.addAll(copiedConstraintsRightToLeft); } } return results; }</code><technical_language>![MAJOR](<LINK_1> Cyclomatic Complexity of this method "setConstraint" is 12 is greater 10 authorized. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public List<ProgramState> setConstraint(ProgramState initialProgramState, BooleanConstraint booleanConstraint) { ProgramState programState = initialProgramState; if (leftOp.equals(rightOp)) { if (shouldNotInverse().equals(booleanConstraint)) { return ImmutableList.of(programState); } return ImmutableList.of(); } programState = checkRelation(booleanConstraint, programState); if (programState == null) { return ImmutableList.of(); } List<ProgramState> copiedConstraints = copyConstraint(leftOp, rightOp, programState, booleanConstraint); if (copiedConstraints.isEmpty()) { return ImmutableList.of(); } List<ProgramState> results = new ArrayList<>(); for (ProgramState ps : copiedConstraints) { List<ProgramState> copiedConstraintsRightToLeft = copyConstraint(rightOp, leftOp, ps, booleanConstraint); if (copiedConstraintsRightToLeft.size() == 1 && copiedConstraintsRightToLeft.get(0).equals(programState)) { results.add(programState.addConstraint(this, booleanConstraint)); } else { results.addAll(copiedConstraintsRightToLeft); } } return results; }
Source:
<code>public void pack () { checkWidget(); int width = 0; if (buttonHandle != 0 && parent.getHeaderVisible() && <START> !GTK.gtk_widget_get_visible(buttonHandle)) <END> { GtkRequisition requisition = new GtkRequisition (); GTK.gtk_widget_show(buttonHandle); gtk_widget_get_preferred_size (buttonHandle, requisition); GTK.gtk_widget_hide(buttonHandle); width = requisition.width; } if ((parent.style & SWT.VIRTUAL) != 0) { boolean calcWidth = false; Rectangle itemBounds = null; int tableHeight = 0; if (parent.isVisible()) { Rectangle tableBounds = parent.getBounds(); tableHeight = tableBounds.height - parent.getHeaderHeight(); } else { calcWidth = true; } for (int i=0; i<parent.items.length; i++) { TableItem item = parent.items [i]; if (itemBounds == null && item != null) itemBounds = item.getBounds(); boolean isVisible = false; if (!calcWidth && itemBounds != null) { int itemTopBound = itemBounds.y + itemBounds.height * i + i; int itemBottomBound = itemTopBound + itemBounds.height; isVisible = (itemTopBound > 0 && itemBottomBound < tableHeight); } if (item != null && item.cached && (isVisible || calcWidth)) { width = Math.max (width, parent.calculateWidth (handle, item.handle)); } } } else { long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); if (GTK.gtk_tree_model_get_iter_first (parent.modelHandle, iter)) { do { width = Math.max (width, parent.calculateWidth (handle, iter)); } while (GTK.gtk_tree_model_iter_next(parent.modelHandle, iter)); } OS.g_free (iter); } setWidthInPixels(width); }</code><technical_language>I understand this. If button handle is visible, check size</technical_language>

Target:
public void pack () { checkWidget(); int width = 0; if (buttonHandle != 0) { boolean hideHeader = !GTK.gtk_widget_get_visible(buttonHandle); GtkRequisition requisition = new GtkRequisition (); GTK.gtk_widget_show(buttonHandle); gtk_widget_get_preferred_size (buttonHandle, requisition); if (hideHeader) { GTK.gtk_widget_hide(buttonHandle); } width = requisition.width; } if ((parent.style & SWT.VIRTUAL) != 0) { boolean calcWidth = false; Rectangle itemBounds = null; int tableHeight = 0; if (parent.isVisible()) { Rectangle tableBounds = parent.getBounds(); tableHeight = tableBounds.height - parent.getHeaderHeight(); } else { calcWidth = true; } for (int i=0; i<parent.items.length; i++) { TableItem item = parent.items [i]; if (itemBounds == null && item != null) itemBounds = item.getBounds(); boolean isVisible = false; if (!calcWidth && itemBounds != null) { int itemTopBound = itemBounds.y + itemBounds.height * i + i; int itemBottomBound = itemTopBound + itemBounds.height; isVisible = (itemTopBound > 0 && itemBottomBound < tableHeight); } if (item != null && item.cached && (isVisible || calcWidth)) { width = Math.max (width, parent.calculateWidth (handle, item.handle)); } } } else { long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); if (GTK.gtk_tree_model_get_iter_first (parent.modelHandle, iter)) { do { width = Math.max (width, parent.calculateWidth (handle, iter)); } while (GTK.gtk_tree_model_iter_next(parent.modelHandle, iter)); } OS.g_free (iter); } setWidthInPixels(width); }
Source:
<code>private void initializeCtrlTaskContextId() { <START> if (dolphinDriver == null) { <END> throw new RuntimeException("Cannot resolve ctrlTaskContextId because InjectionFuture<DolphinDriver> is null"); } ctrlTaskContextId = dolphinDriver.get().getCtrlTaskContextId(); }</code><technical_language>check dolphinDriver is null in constructor? If so, is a problem earlier</technical_language>

Target:
private void initializeCtrlTaskContextId() { ctrlTaskContextId = dolphinDriver.get().getCtrlTaskContextId(); }
Source:
<code><START> public void disableTemperatureNotifications() { <END> BluetoothLeGattCharacteristic tempValueChar; try { tempValueChar = this.gattServices.get(TEMPERATURE) .findCharacteristic(TiSensorTagGatt.UUID_TEMP_SENSOR_VALUE); tempValueChar.disableValueNotifications(); } catch (KuraException e) { logger.error("Temperature notification disable failed", e); } }</code><technical_language>Similarly return boolean signify success of this method invocation</technical_language>

Target:
public boolean disableTemperatureNotifications() { boolean result = false; BluetoothLeGattCharacteristic tempValueChar; try { tempValueChar = this.gattServices.get(TEMPERATURE) .findCharacteristic(TiSensorTagGatt.UUID_TEMP_SENSOR_VALUE); tempValueChar.disableValueNotifications(); result = true; } catch (KuraException e) { logger.error("Temperature notification disable failed", e); } return result; }
Source:
<code>private void addConfigurationFields() { Group configGroup = Form.createGroup(this, 2, Messages.getString("DataBricksInfoForm.text.configuration"), 110); configGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); <START> labelledCombo = new LabelledCombo(configGroup, "Cloud provider", "", cloudProviders); <END> endpointText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.endPoint"), 1); clusterIDText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.clusterID"), 1); tokenText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.token"), 1, SWT.PASSWORD | SWT.BORDER | SWT.SINGLE); dbfsDepFolderText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.dbfsDepFolder"), 1); }</code><technical_language>Please support i18n</technical_language>

Target:
private void addConfigurationFields() { Group configGroup = Form.createGroup(this, 2, Messages.getString("DataBricksInfoForm.text.configuration"), 110); configGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); cloudProviderCombo = new LabelledCombo(configGroup, Messages.getString("DataBricksInfoForm.text.cloudProvider"), "", getProviders()); endpointText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.endPoint"), 1); clusterIDText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.clusterID"), 1); tokenText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.token"), 1, SWT.PASSWORD | SWT.BORDER | SWT.SINGLE); dbfsDepFolderText = new LabelledText(configGroup, Messages.getString("DataBricksInfoForm.text.dbfsDepFolder"), 1); }
Source:
<code>private static <B extends Message.Builder> Class<B> getBuilderForType(TypeUrl typeUrl) { Class<B> builderClass; final String className = KnownTypes.getClassName(typeUrl) .value(); try { builderClass = (Class<B>) Class.forName(className) .getClasses()[0]; } catch (ClassNotFoundException e) { final String message = String.format( "Class for name %s could not be found. Try to rebuild the project. Make sure \"known_types.properties\" exists.", className); log().warn(message, e); builderClass = null; } catch (ClassCastException e) { final String message = String.format( <START> "Class %s Must be assignable from com.google.protobuf.Message. Try to rebuild the project. Make sure type URL is valid.", <END> className); log().warn(message, e); builderClass = null; } return builderClass; }</code><technical_language>Please extract string literals constants</technical_language>

Target:
private static <B extends Message.Builder> Class<B> getBuilderForType(TypeUrl typeUrl) { Class<B> builderClass; final String className = KnownTypes.getClassName(typeUrl) .value(); try { builderClass = (Class<B>) Class.forName(className) .getClasses()[0]; } catch (ClassNotFoundException e) { final String message = String.format( BUILDER_CLASS_ERROR_LOGGING_PATTERN, className); log().warn(message, e); builderClass = null; } catch (ClassCastException e) { final String message = String.format( TYPE_CAST_ERROR_LOGGING_PATTERN, className); log().warn(message, e); builderClass = null; } return builderClass; }