auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void hdfsSink(Object payload) { <START> if (payload != null) { <END> try { dataStoreWriter.write(payload.toString()); } catch (IOException e) { throw new IllegalStateException("Error while writing to HDFS", e); } } }</code><technical_language>SI send null payload</technical_language>

Target:
public void hdfsSink(Object payload) { try { dataStoreWriter.write(payload.toString()); } catch (IOException e) { throw new IllegalStateException("Error while writing to HDFS", e); } }
Source:
<code>public static void removeStatusCookie(HttpServletRequest req, HttpServletResponse resp) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { <START> if (cookie.getName().equals(OAuthConstants.STATUSCOOKIE)) { <END> cookie.setMaxAge(0); resp.addCookie(cookie); break; } } } }</code><technical_language>check equals, constant</technical_language>

Target:
public static void removeStatusCookie(HttpServletRequest req, HttpServletResponse resp) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (OAuthConstants.STATUSCOOKIE.equals(cookie.getName())) { cookie.setMaxAge(0); resp.addCookie(cookie); break; } } } }
Source:
<code>public void environmentVariablesSubstitutionInThemeProperties() { testingClient.server().run(session -> { try { ThemeProvider extending = session.getProvider(ThemeProvider.class, "extending"); Theme theme = extending.getTheme(THEME_NAME, Theme.Type.LOGIN); Assert.assertEquals("", theme.getProperties().getProperty("env.missing")); Assert.assertEquals("defaultValue", theme.getProperties().getProperty("env.missingWithDefault")); if (System.getenv().containsKey("HOMEPATH")) { Assert.assertEquals(System.getenv().get("HOMEPATH"), theme.getProperties().getProperty("env.windowsHome")); <START> } else if (System.getenv().containsKey("HOME")) { <END> Assert.assertEquals(System.getenv().get("HOME"), theme.getProperties().getProperty("env.linuxHome")); } else { Assert.fail("No default env variable found, can't verify"); } } catch (IOException e) { Assert.fail(e.getMessage()); } }); }</code><technical_language>Need confirm if this is set Mac</technical_language>

Target:
public void environmentVariablesSubstitutionInThemeProperties() { testingClient.server().run(session -> { try { ThemeProvider extending = session.getProvider(ThemeProvider.class, "extending"); Theme theme = extending.getTheme(THEME_NAME, Theme.Type.LOGIN); Assert.assertEquals("${env.MISSING_ENVIRONMENT_VARIABLE}", theme.getProperties().getProperty("env.missing")); Assert.assertEquals("defaultValue", theme.getProperties().getProperty("env.missingWithDefault")); if (System.getenv().containsKey("HOMEPATH")) { Assert.assertEquals(System.getenv().get("HOMEPATH"), theme.getProperties().getProperty("env.windowsHome")); } else if (System.getenv().containsKey("HOME")) { Assert.assertEquals(System.getenv().get("HOME"), theme.getProperties().getProperty("env.unixHome")); } else { Assert.fail("No default env variable found, can't verify"); } } catch (IOException e) { Assert.fail(e.getMessage()); } }); }
Source:
<code>public void sendMessageAsync(final String destAddress, final String message, final boolean command) { <START> new Thread(new Runnable() { <END> public void run() { try { sendMessageSync(destAddress, message, command); } catch (MessageException | InterruptedException error) { Log.warning(error); } } }).start(); }</code><technical_language>I is request().async().post() instead of creating new thread</technical_language>

Target:
public void sendMessageAsync(final String destAddress, final String message, final boolean command) { getRequestBuilder().async().post(Entity.json(preparePayload(destAddress, message))); }
Source:
<code>private Severity errorLevel(Level level) { if (level.name().equals(Level.Error())) { return Severity.ERROR; <START> } else if (level.name().equals(Level.Info())) { <END> return Severity.INFO; } else if (level.name().equals(Level.Warning())) { return Severity.WARNING; } else { LOG.warn("Got unrecognized severity level: {}", level); return Severity.IGNORE; } }</code><technical_language>else is needed</technical_language>

Target:
private Severity errorLevel(Level level) { if (level.name().equals(Level.Error())) { return Severity.ERROR; } else if (level.name().equals(Level.Info())) { return Severity.INFO; } else if (level.name().equals(Level.Warning())) { return Severity.WARNING; } LOG.warn("Got unrecognized severity level: {}", level); return Severity.IGNORE; }
Source:
<code>Mono<PagedResponse<ModelData>> listModelsSinglePageAsync(ListModelOptions listModelOptions, Context context){ return protocolLayer.getDigitalTwinModels().listSinglePageAsync( listModelOptions.getDependenciesFor(), listModelOptions.getIncludeModelDefinition(), new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()), context) .map( objectPagedResponse -> { List<ModelData> convertedList = objectPagedResponse.getValue().stream() <START> .map(object -> ModelDataConverter.map(object)) <END> .filter(Objects::nonNull) .collect(Collectors.toList()); return new PagedResponseBase<>( objectPagedResponse.getRequest(), objectPagedResponse.getStatusCode(), objectPagedResponse.getHeaders(), convertedList, null, ((PagedResponseBase) objectPagedResponse).getDeserializedHeaders()); } ); }</code><technical_language>method reference -> calling a static method replaced a method reference</technical_language>

Target:
Mono<PagedResponse<ModelData>> listModelsSinglePageAsync(ListModelOptions listModelOptions, Context context){ return protocolLayer.getDigitalTwinModels().listSinglePageAsync( listModelOptions.getDependenciesFor(), listModelOptions.getIncludeModelDefinition(), new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()), context) .map( objectPagedResponse -> { List<ModelData> convertedList = objectPagedResponse.getValue().stream() .map(ModelDataConverter::map) .filter(Objects::nonNull) .collect(Collectors.toList()); return new PagedResponseBase<>( objectPagedResponse.getRequest(), objectPagedResponse.getStatusCode(), objectPagedResponse.getHeaders(), convertedList, null, ((PagedResponseBase) objectPagedResponse).getDeserializedHeaders()); } ); }
Source:
<code>protected void run() { try (Git git = new Git(db)) { CommitCommand commitCmd = git.commit(); if (author != null) commitCmd.setAuthor(RawParseUtils.parsePersonIdent(author)); if (message != <START> null) { <END> commitCmd.setMessage(message); } if (noGpgSign) { commitCmd.setSign(Boolean.FALSE); } else if (gpgSigningKey != null) { commitCmd.setSign(Boolean.TRUE); if (!gpgSigningKey.equals(GpgSignHandler.DEFAULT)) { commitCmd.setSigningKey(gpgSigningKey); } } if (only && paths.isEmpty()) { throw die(CLIText.get().pathsRequired); } if (only && all) { throw die(CLIText.get().onlyOneOfIncludeOnlyAllInteractiveCanBeUsed); } if (!paths.isEmpty()) { for (String p : paths) { commitCmd.setOnly(p); } } commitCmd.setAmend(amend); commitCmd.setAll(all); Ref head = db.exactRef(Constants.HEAD); if (head == null) { throw die(CLIText.get().onBranchToBeBorn); } RevCommit commit; try { commit = commitCmd.call(); } catch (JGitInternalException | GitAPIException e) { throw die(e.getMessage(), e); } String branchName; if (!head.isSymbolic()) { branchName = CLIText.get().branchDetachedHEAD; } else { branchName = head.getTarget().getName(); if (branchName.startsWith(Constants.R_HEADS)) { branchName = branchName.substring(Constants.R_HEADS.length()); } } outw.println("[" + branchName + " " + commit.name() + "] " + commit.getShortMessage()); } catch (IOException e) { throw die(e.getMessage(), e); } }</code><technical_language>Add missing braces in a separate commit</technical_language>

Target:
protected void run() { try (Git git = new Git(db)) { CommitCommand commitCmd = git.commit(); if (author != null) commitCmd.setAuthor(RawParseUtils.parsePersonIdent(author)); if (message != null) commitCmd.setMessage(message); if (noGpgSign) { commitCmd.setSign(Boolean.FALSE); } else if (gpgSigningKey != null) { commitCmd.setSign(Boolean.TRUE); if (!gpgSigningKey.equals(GpgSignHandler.DEFAULT)) { commitCmd.setSigningKey(gpgSigningKey); } } if (only && paths.isEmpty()) throw die(CLIText.get().pathsRequired); if (only && all) throw die(CLIText.get().onlyOneOfIncludeOnlyAllInteractiveCanBeUsed); if (!paths.isEmpty()) for (String p : paths) commitCmd.setOnly(p); commitCmd.setAmend(amend); commitCmd.setAll(all); Ref head = db.exactRef(Constants.HEAD); if (head == null) { throw die(CLIText.get().onBranchToBeBorn); } RevCommit commit; try { commit = commitCmd.call(); } catch (JGitInternalException | GitAPIException e) { throw die(e.getMessage(), e); } String branchName; if (!head.isSymbolic()) branchName = CLIText.get().branchDetachedHEAD; else { branchName = head.getTarget().getName(); if (branchName.startsWith(Constants.R_HEADS)) branchName = branchName.substring(Constants.R_HEADS.length()); } outw.println("[" + branchName + " " + commit.name() + "] " + commit.getShortMessage()); } catch (IOException e) { throw die(e.getMessage(), e); } }
Source:
<code>public BlobProperties downloadToFile(String filePath) { downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE); <START> return getProperties(); <END> }</code><technical_language>calling getProperties here? call getValue call above</technical_language>

Target:
public BlobProperties downloadToFile(String filePath) { return downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE).getValue(); }
Source:
<code>protected void setupGrid() { GridPane grid = new GridPane(); setupGridPane(grid); setTitle("Save board as"); <START> <END> HBox nameArea = new HBox(); Text prompt = new Text("New board name: "); nameField = new TextField(DEFAULT_NAME); nameField.setPrefWidth(300); Platform.runLater(() -> { nameField.requestFocus(); }); nameField.setId("boardnameinput"); nameArea.getChildren().addAll(prompt, nameField); grid.add(nameArea, 0, 0); errorText = new Text(""); grid.add(errorText, 0, 1); getDialogPane().setContent(grid); }</code><technical_language>"Save board ..."</technical_language>

Target:
protected void setupGrid() { GridPane grid = new GridPane(); setupGridPane(grid); setTitle(BOARD_DIALOG_NAME); HBox nameArea = new HBox(); Text prompt = new Text("New board name: "); nameField = new TextField(DEFAULT_NAME); nameField.setPrefWidth(300); Platform.runLater(() -> { nameField.requestFocus(); }); nameField.setId("boardnameinput"); nameArea.getChildren().addAll(prompt, nameField); grid.add(nameArea, 0, 0); errorText = new Text(""); errorText.getStyleClass().add("text-red"); grid.add(errorText, 0, 1); getDialogPane().setContent(grid); }
Source:
<code><START> protected synchronized void executeFunctionsUponCommit() { <END> if (uponCommitFunctions != null) { executeFunctions(uponCommitFunctions); uponCommitFunctions = null; } }</code><technical_language>If theoretically ISPN call methods more (for a transaction), implementation needs do more ensure synchronized access methods: needs ensure methods effect once, time method is called</technical_language>

Target:
protected void executeFunctionsUponCommit() { if (uponCommitFunctions != null) { executeFunctions(uponCommitFunctions); uponCommitFunctions = null; } }
Source:
<code>RefUpdate newUpdate(final String name, boolean detach) throws IOException { refreshPackedRefs(); Ref r = readRefBasic(name, 0); if (detach) { if (r == null) r = new Ref(Ref.Storage.NEW, name, null); else { <START> r = peel(r); <END> r = new Ref(Ref.Storage.NEW, name, r.getPeeledObjectId()); } } else { if (r == null) r = new Ref(Ref.Storage.NEW, name, null); } return new RefUpdate(this, r, fileForRef(r.getName())); }</code><technical_language>peeling ref if exists? exact ObjectId currently points peeled identity</technical_language>

Target:
RefUpdate newUpdate(final String name, boolean detach) throws IOException { refreshPackedRefs(); Ref r = readRefBasic(name, 0); if (r == null) r = new Ref(Ref.Storage.NEW, name, null); else if (detach) r = new Ref(Ref.Storage.NEW, name, r.getObjectId()); return new RefUpdate(this, r, fileForRef(r.getName())); }
Source:
<code>private boolean isSameHosts(final String name1, final String name2) { String hostname1 = name1 == null ? "" : name1.trim(); String hostname2 = name2 == null ? "" : name2.trim(); if (hostname1.equals(hostname2)) { return true; } String localHost = "localhost"; <START> String localHostName = localHost; <END> try { localHostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { } if (hostname1.length() == 0) { hostname1 = localHostName; } if (hostname2.length() == 0) { hostname2 = localHostName; } if (hostname1.equals(hostname2)) { return true; } if ((hostname1.equals(localHost) && hostname2.equals(localHostName)) || (hostname1.equals(localHostName) && hostname2.equals(localHost))) { return true; } try { String ipAddress1 = InetAddress.getByName(hostname1).getHostAddress(); String ipAddress2 = InetAddress.getByName(hostname2).getHostAddress(); return ipAddress1.equals(ipAddress2); } catch (UnknownHostException ex) { } return false; }</code><technical_language>do need 2 local variables for purpose</technical_language>

Target:
private boolean isSameHosts(final String name1, final String name2) { String hostname1 = name1 == null ? "" : name1.trim(); String hostname2 = name2 == null ? "" : name2.trim(); if (hostname1.equals(hostname2)) return true; String localHost = "localhost"; String resolvedHostName; try { resolvedHostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { resolvedHostName = localHost; } if (hostname1.length() == 0) hostname1 = resolvedHostName; if (hostname2.length() == 0) hostname2 = resolvedHostName; if (hostname1.equals(hostname2)) return true; if ((hostname1.equals(localHost) && hostname2.equals(resolvedHostName)) || (hostname1.equals(resolvedHostName) && hostname2.equals(localHost))) return true; try { String ipAddress1 = InetAddress.getByName(hostname1).getHostAddress(); String ipAddress2 = InetAddress.getByName(hostname2).getHostAddress(); return ipAddress1.equals(ipAddress2); } catch (UnknownHostException ex) { } return false; }
Source:
<code>public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } <START> discussionPostsAdapter.insert(newThread, 0); <END> ((TaskProcessCallback) getActivity()).onMessage(MessageType.EMPTY, ""); } }</code><technical_language>Hmm, previous implementation fine here. adding new threads top of pinned threads. new filtering check is good I guess. add smooth scrolling new item well</technical_language>

Target:
public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(newThread, i); discussionPostsListView.setSelection(i); ((TaskProcessCallback) getActivity()).onMessage(MessageType.EMPTY, ""); } }
Source:
<code><START> public void testCommitFailure() throws Exception { <END> Properties props = createProps(); HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailAppend(true); hdfsWriter.write(sinkRecords); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, topicsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); for (String entry: data.keySet()) { System.out.println(entry); } content = data.get(logFile); assertEquals(2, content.size()); hdfsWriter.close(); }</code><technical_language>validate correct backoff in tests? is a mock context object, easy validate</technical_language>

Target:
public void testCommitFailure() throws Exception { Properties props = createProps(); HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailure(MemoryStorage.Failure.appendFailure); hdfsWriter.write(sinkRecords); assertEquals(context.backoff(), connectorConfig.getLong(HdfsSinkConnectorConfig.RETRY_BACKOFF_CONFIG)); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, topicsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(null, content); Thread.sleep(context.backoff()); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(2, content.size()); hdfsWriter.close(); }
Source:
<code>public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs < 0) <START> logger.warn("skipping block-for-peers due to negative timeout. You may encounter errors or timeouts on" + <END> " the first user query"); if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }</code><technical_language>this a warning? pretty asked for it</technical_language>

Target:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }
Source:
<code>public void onEvent(Event e) { if (isReloadConfigEvent(e)) { handleReloadEvent(e); return; } if (getName().equals(e.getSource())) { LOG.debug("onEvent: ignoring event with EventTranslator as source"); return; } List<Event> translated = m_config.translateEvent(e); if (translated != null) { if (translated.isEmpty()) { <START> LOG.debug("onEvent: received event that matches no translations: \n", EventUtils.toString(e)); <END> return; } LOG.debug("onEvent: received valid registered translation event: \n", EventUtils.toString(e)); Log log = new Log(); Events events = new Events(); for (Iterator<Event> iter = translated.iterator(); iter.hasNext();) { Event event = iter.next(); events.addEvent(event); LOG.debug("onEvent: sended translated event: \n", EventUtils.toString(event)); } log.setEvents(events); getEventManager().sendNow(log); } }</code><technical_language>{} placeholder show event in this message. avoid calling EventUtils.toString() DEBUG logging is enabled. (I realize this existing code, change while here.)</technical_language>

Target:
public void onEvent(Event e) { if (isReloadConfigEvent(e)) { handleReloadEvent(e); return; } if (getName().equals(e.getSource())) { LOG.debug("onEvent: ignoring event with EventTranslator as source"); return; } List<Event> translated = m_config.translateEvent(e); if (translated != null) { if (translated.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("onEvent: received event that matches no translations: {}", EventUtils.toString(e)); } return; } if (LOG.isDebugEnabled()) { LOG.debug("onEvent: received valid register ed translation event: {}", EventUtils.toString(e)); } Log log = new Log(); Events events = new Events(); for (Iterator<Event> iter = translated.iterator(); iter.hasNext();) { Event event = iter.next(); events.addEvent(event); if (LOG.isDebugEnabled()) { LOG.debug("onEvent: sended translated event: {}", EventUtils.toString(e)); } } log.setEvents(events); getEventManager().sendNow(log); } }
Source:
<code>private static String computeProcessingID(final String dataSource, final List<DataSegment> segments) { final String segmentIDs = Joiner.on("_").join( Iterables.transform( Ordering.natural().sortedCopy(segments), new Function<DataSegment, String>() { @Override public String apply(DataSegment x) { return String.format( "%s_%s_%s_%s", x.getInterval().getStart(), x.getInterval().getEnd(), x.getVersion(), x.getShardSpec().getPartitionNum() ); } } ) ); <START> return String.format("%s_%s", dataSource, DigestUtils.sha1Hex(segmentIDs).toLowerCase()); <END> }</code><technical_language>swap Guava Hashing instead of DigestUtils</technical_language>

Target:
private static String computeProcessingID(final String dataSource, final List<DataSegment> segments) { final String segmentIDs = Joiner.on("_").join( Iterables.transform( Ordering.natural().sortedCopy(segments), new Function<DataSegment, String>() { @Override public String apply(DataSegment x) { return String.format( "%s_%s_%s_%s", x.getInterval().getStart(), x.getInterval().getEnd(), x.getVersion(), x.getShardSpec().getPartitionNum() ); } } ) ); return String.format( "%s_%s", dataSource, Hashing.sha1().hashString(segmentIDs, Charsets.UTF_8).toString().toLowerCase() ); }
Source:
<code>public NodeValue getAccValue() { double mode= Double.NaN; if ( count == 0 ) return noValuesToMode ; if ( super.errorCount != 0 ) return null ; int indexsize = collection.size(); double[] arrDouble = new double[indexsize]; for(int i=0; i<indexsize; i++){ arrDouble[i] = collection.get(i).getDouble(); } HashMap<Double,Integer> amode = new HashMap<Double,Integer>(); int max = 0; for(int i = 0; i < arrDouble.length; i++) { if (amode.get(arrDouble[i]) != null) { int count = amode.get(arrDouble[i]); count++; amode.put(arrDouble[i], count); if(count > max) { max = count; mode = arrDouble[i]; } } else { amode.put(arrDouble[i],1); if(mode==0) { mode = arrDouble[i]; } } } for (Map.Entry<Double, Integer> entry: amode.entrySet()) { if (entry.getValue() == max) { <START> System.out.println("Print all max: "+entry.getKey()+" Count: "+entry.getValue()); <END> } } return (NodeValue.makeDecimal(mode)); }</code><technical_language>This a proper logging statement</technical_language>

Target:
public NodeValue getAccValue() { double mode= Double.NaN; if ( count == 0 ) return noValuesToMode ; if ( super.errorCount != 0 ) return null ; int indexsize = collection.size(); double[] arrDouble = new double[indexsize]; for(int i=0; i<indexsize; i++){ arrDouble[i] = collection.get(i).getDouble(); } HashMap<Double,Integer> amode = new HashMap<Double,Integer>(); int max = 0; for(int i = 0; i < arrDouble.length; i++) { if (amode.get(arrDouble[i]) != null) { int count = amode.get(arrDouble[i]); count++; amode.put(arrDouble[i], count); if(count > max) { max = count; mode = arrDouble[i]; } } else { amode.put(arrDouble[i],1); if(mode==0) { mode = arrDouble[i]; } } } return NodeValue.makeDecimal(mode); }
Source:
<code>public void testAddItem() { final Element enumerationItem = mock(Element.class); final DragAndDropHelper helper = mock(DragAndDropHelper.class); items.childNodes = mock(NodeList.class); doReturn(helper).when(view).getDragAndDropHelper(); view.addItem(enumerationItem); verify(items).appendChild(enumerationItem); verify(helper).refreshItemsPosition(); <START> } <END></code><technical_language>I need check property "data-position" set</technical_language>

Target:
public void testAddItem() { final Element enumerationItem = mock(Element.class); final DragAndDropHelper helper = mock(DragAndDropHelper.class); items.childNodes = mock(NodeList.class); doReturn(helper).when(view).getDragAndDropHelper(); view.addItem(enumerationItem); verify(items).appendChild(enumerationItem); verify(helper).refreshItemsPosition(); verify(enumerationItem).setAttribute(DATA_POSITION, 0); }
Source:
<code>public void testFreestyleWithIOExceptionPublisher() throws IOException, ExecutionException, InterruptedException { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new IOExceptionPublisher()); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); p.getPublishersList().add(new ArtifactArchiver("result.txt", "", false)); FreeStyleBuild b = p.scheduleBuild2(0).get(); <START> assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); <END> File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails.", file.exists()); assertTrue("Second publisher must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); }</code><technical_language>FalsePublisher -> IOExceptionPublisher</technical_language>

Target:
public void testFreestyleWithIOExceptionPublisher() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new IOExceptionPublisher()); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt"); artifactArchiver.setOnlyIfSuccessful(false); p.getPublishersList().add(artifactArchiver); FreeStyleBuild b = p.scheduleBuild2(0).get(); assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); j.assertLogContains("\tat hudson.model.utils.IOExceptionPublisher", b); j.assertLogContains("Threw IOException from publisher!", b); File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); assertTrue("Third publisher must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); }
Source:
<code>} catch (IntrospectionException ie) { <START> ie.printStackTrace(); <END> }</code><technical_language>logger and/or rethrow exception instead of printing stack trace</technical_language>

Target:
} catch (IntrospectionException ie) { LOG.warn("Failed to introspect OnmsAssetRecord when initializing due to {}", ie.getLocalizedMessage()); }
Source:
<code>public void execute() throws FluoCommandException { if (args.size() < 2) { throw new FluoCommandException("Usage: fluo exec <app> <class> args..."); } final String applicationName = args.get(0); final String className = args.get(1); FluoConfiguration fluoConfig = CommandUtil.resolveFluoConfig(); fluoConfig.setApplicationName(applicationName); CommandUtil.verifyAppInitialized(fluoConfig); fluoConfig = FluoAdminImpl.mergeZookeeperConfig(fluoConfig); try { Class<?> clazz = Class.forName(className); Guice.createInjector(new FluoConfigModule(clazz, fluoConfig)); Method method = clazz.getMethod("main", String[].class); method.invoke(null, args.subList(2, args.size())); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { <START> throw new FluoCommandException(String.format("Class %s must have a main method", className), <END> e); } catch (ClassNotFoundException e) { throw new FluoCommandException(String.format("Class %s not found", className), e); } }</code><technical_language>Nice error messages</technical_language>

Target:
public void execute() throws FluoCommandException { if (args.size() < 2) { throw new FluoCommandException("Usage: fluo exec <app> <class> args..."); } final String applicationName = args.get(0); final String className = args.get(1); FluoConfiguration fluoConfig = CommandUtil.resolveFluoConfig(); fluoConfig.setApplicationName(applicationName); CommandUtil.verifyAppInitialized(fluoConfig); fluoConfig = FluoAdminImpl.mergeZookeeperConfig(fluoConfig); try { Class<?> clazz = Class.forName(className); Guice.createInjector(new FluoConfigModule(clazz, fluoConfig)); Method method = clazz.getMethod("main", String[].class); List<String> execArgs = args.subList(2, args.size()); method.invoke(null, (Object) execArgs.toArray(new String[execArgs.size()])); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new FluoCommandException(String.format("Class %s must have a main method", className), e); } catch (ClassNotFoundException e) { throw new FluoCommandException(String.format("Class %s not found", className), e); } }
Source:
<code>public void addConnection(PhoenixConnection connection) throws SQLException { if (returnSequenceValues || shouldThrottleNumConnections) { synchronized (connectionCountLock) { if(shouldThrottleNumConnections) { int futureConnections = 1 + ( connection.isInternalConnection() ? internalConnectionCount : connectionCount); int allowedConnections = connection.isInternalConnection() ? maxInternalConnectionsAllowed : maxConnectionsAllowed; if(allowedConnections != 0 && futureConnections > allowedConnections) { <START> GLOBAL_PHOENIX_CONNECTIONS_THROTTLED_COUNTER.increment(); <END> throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_CONNECTION_THROTTLED). build().buildException(); } } if(!connection.isInternalConnection()) { connectionCount++; } else { internalConnectionCount++; } } } if (isRenewingLeasesEnabled()) { connectionQueues.get(getQueueIndex(connection)).add(new WeakReference<PhoenixConnection>(connection)); } }</code><technical_language>of shouldThrottleNumConnections set based this internal conn config max num conns a client right</technical_language>

Target:
public void addConnection(PhoenixConnection connection) throws SQLException { if (returnSequenceValues || shouldThrottleNumConnections) { synchronized (connectionCountLock) { if(shouldThrottleNumConnections) { int futureConnections = 1 + ( connection.isInternalConnection() ? internalConnectionCount : connectionCount); int allowedConnections = connection.isInternalConnection() ? maxInternalConnectionsAllowed : maxConnectionsAllowed; if(allowedConnections != 0 && futureConnections > allowedConnections) { GLOBAL_PHOENIX_CONNECTIONS_THROTTLED_COUNTER.increment(); if(connection.isInternalConnection()) { throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_INTERNAL_CONNECTION_THROTTLED). build().buildException(); } throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_CONNECTION_THROTTLED). build().buildException(); } } if(!connection.isInternalConnection()) { connectionCount++; } else { internalConnectionCount++; } } } if (isRenewingLeasesEnabled()) { connectionQueues.get(getQueueIndex(connection)).add(new WeakReference<PhoenixConnection>(connection)); } }
Source:
<code>private void createNewExperimentNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData data = new GridData(GridData.FILL_HORIZONTAL); <START> data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; <END> String name = fExperiment.getName(); Label newExperimentLabel = new Label(folderGroup, SWT.NONE); newExperimentLabel.setFont(font); newExperimentLabel.setText(Messages.RenameExperimentDialog_ExperimentNewName); fNewExperimentName = new Text(folderGroup, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewExperimentName.setLayoutData(data); fNewExperimentName.setFont(font); fNewExperimentName.setFocus(); fNewExperimentName.setText(name); fNewExperimentName.setSelection(0, name.length()); fNewExperimentName.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewExperimentName(); } }); }</code><technical_language>Unused instance</technical_language>

Target:
private void createNewExperimentNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); String name = fExperiment.getName(); Label newExperimentLabel = new Label(folderGroup, SWT.NONE); newExperimentLabel.setFont(font); newExperimentLabel.setText(Messages.RenameExperimentDialog_ExperimentNewName); fNewExperimentName = new Text(folderGroup, SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewExperimentName.setLayoutData(data); fNewExperimentName.setFont(font); fNewExperimentName.setFocus(); fNewExperimentName.setText(name); fNewExperimentName.setSelection(0, name.length()); fNewExperimentName.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewExperimentName(); } }); }
Source:
<code>private boolean isImagesExists() { <START> for (DiskImage diskImage : getSourceImages()) { <END> if (diskImage.getDiskStorageType() == DiskStorageType.IMAGE) { return true; } } return false; }</code><technical_language>for readability, consider 'ImagesHandler.filterImageDisks' check if empty..</technical_language>

Target:
private boolean isImagesExists() { List<DiskImage> disks = ImagesHandler.filterImageDisks(getSourceImages(), true, false, true); return !disks.isEmpty(); }
Source:
<code>public Future<String> asyncRemoteCancelMethod() throws InterruptedException { try { <START> System.out.println("ASYNC REMOTE "); <END> String result; result = ctx.wasCancelCalled() ? "true" : "false"; System.out.println("DO COUNTDOWN "); synchronizeBean.latchCountDown(); long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { if (ctx.wasCancelCalled()) { break; } Thread.sleep(50); } result += ";"; result += ctx.wasCancelCalled() ? "true" : "false"; return new AsyncResult<String>(result); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }</code><technical_language>This removed</technical_language>

Target:
public Future<String> asyncRemoteCancelMethod() throws InterruptedException { String result; result = ctx.wasCancelCalled() ? "true" : "false"; synchronizeBean.latchCountDown(); long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { if (ctx.wasCancelCalled()) { break; } Thread.sleep(50); } result += ";"; result += ctx.wasCancelCalled() ? "true" : "false"; return new AsyncResult<String>(result); }
Source:
<code>private void writeHierarchyInfo( SaxWriter writer, List<Hierarchy> hierarchies, List<Property> props) { writer.startSequence(null, "HierarchyInfo"); for (Hierarchy hierarchy : hierarchies) { writer.startElement( "HierarchyInfo", "name", hierarchy.getName()); for (final Property prop : props) { if (prop instanceof IMondrianOlap4jProperty) { IMondrianOlap4jProperty currentProperty = (IMondrianOlap4jProperty) prop; <START> String thisHierarchiName = hierarchy.getName(); <END> String thatHierarchiName = currentProperty.getLevel() .getHierarchy().getName(); if (thisHierarchiName.equals(thatHierarchiName)) { final String encodedProp = encoder .encode(prop.getName()); final Object[] attributes = getAttributes( prop, hierarchy); writer.element(encodedProp, attributes); } } else { final String encodedProp = encoder.encode( prop.getName()); final Object[] attributes = getAttributes( prop, hierarchy); writer.element(encodedProp, attributes); } } writer.endElement(); } writer.endSequence(); }</code><technical_language>spelling? thisHierarchyName</technical_language>

Target:
private void writeHierarchyInfo( SaxWriter writer, List<Hierarchy> hierarchies, List<Property> props) { writer.startSequence(null, "HierarchyInfo"); for (Hierarchy hierarchy : hierarchies) { writer.startElement( "HierarchyInfo", "name", hierarchy.getName()); for (final Property prop : props) { if (prop instanceof IMondrianOlap4jProperty) { writeProperty(writer, hierarchy, prop); } else { writeElement(writer, hierarchy, prop); } } writer.endElement(); } writer.endSequence(); }
Source:
<code>public void onResume(ClientContext context) throws InsertException, ResumeFailedException { assert(persistent); synchronized(this) { if(resumed) return; resumed = true; } this.context = context; try { raf.onResume(context); originalData.onResume(context); this.storage = new SplitFileInserterStorage(raf, originalData, this, context.fastWeakRandom, context.memoryLimitedJobRunner, context.getJobRunner(true), context.ticker, context.getChkInsertScheduler(realTime).fetchingKeys(), context.persistentFG, context.persistentFileTracker, context.getPersistentMasterSecret()); storage.onResume(context); synchronized(this) { <START> this.sender = new SplitFileInserterSender(this, storage); <END> } schedule(context); } catch (IOException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (StorageFormatException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (ChecksumFailedException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } }</code><technical_language>assigning this reference need lock? (Although I a copy of _Java Concurrency In Practice_ I read it.)</technical_language>

Target:
public void onResume(ClientContext context) throws InsertException, ResumeFailedException { assert(persistent); synchronized(this) { if(resumed) return; resumed = true; } this.context = context; try { raf.onResume(context); originalData.onResume(context); this.storage = new SplitFileInserterStorage(raf, originalData, this, context.fastWeakRandom, context.memoryLimitedJobRunner, context.getJobRunner(true), context.ticker, context.getChkInsertScheduler(realTime).fetchingKeys(), context.persistentFG, context.persistentFileTracker, context.getPersistentMasterSecret()); storage.onResume(context); this.sender = new SplitFileInserterSender(this, storage); schedule(context); } catch (IOException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (StorageFormatException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (ChecksumFailedException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } }
Source:
<code>public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); <START> if (this.userPattern != null) { <END> this.userPat = Pattern.compile(this.userPattern); } else { this.userPat = null; } }</code><technical_language>positive conditions 'fail fast' approach improves code readability, e.g. if (this.userPattern == null) { return null; } return Pattern.compile(this.userPattern);</technical_language>

Target:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); if (this.userPattern == null) { this.userPat = null; } else { this.userPat = Pattern.compile(this.userPattern); } }
Source:
<code>private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException ex) { <START> Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded."); <END> } }</code><technical_language>I forgot add ex parameter of Assertions.fail loose failure stacktrace. Please add it</technical_language>

Target:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException exception) { Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded.", exception); } }
Source:
<code>private void assembleDataImport() { server_.assembleDataImport(getOptions(), new ServerRequestCallback<DataImportAssembleResponse>() { @Override public void onResponseReceived(DataImportAssembleResponse response) { if (response.getErrorMessage() != null) { progressIndicator_.onError(response.getErrorMessage()); return; } codePreview_ = response.getImportCode(); dataImportOptionsUi_.setAssembleResponse(response); codeArea_.setCode(codePreview_); <START> codeArea_.getEditor().getSession().setEditorMode(EditorLanguage.LANG_R.getParserName(), false); <END> } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage(codePreviewErrorMessage_, error.getMessage()); } }); }</code><technical_language>turn line numbers well</technical_language>

Target:
private void assembleDataImport() { server_.assembleDataImport(getOptions(), new ServerRequestCallback<DataImportAssembleResponse>() { @Override public void onResponseReceived(DataImportAssembleResponse response) { if (response.getErrorMessage() != null) { progressIndicator_.onError(response.getErrorMessage()); return; } codePreview_ = response.getImportCode(); dataImportOptionsUi_.setAssembleResponse(response); codeArea_.getEditor().getSession().setEditorMode(EditorLanguage.LANG_R.getParserName(), false); codeArea_.getEditor().getRenderer().setShowGutter(false); codeArea_.setCode(codePreview_); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage(codePreviewErrorMessage_, error.getMessage()); } }); }
Source:
<code>public void sendRequestToCatalog(String endpoint, RequestCallback callback) { String endpointToAddToCatalogUrl = endpoint; <START> if (endpoint.startsWith("/")) { <END> endpointToAddToCatalogUrl = endpoint.substring(1); } RequestBuilder request = new RequestBuilder(RequestBuilder.GET, this.catalogUrl + "/" + endpointToAddToCatalogUrl); request.setHeader(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId()); request.setCallback(callback); try { request.send(); } catch (RequestException e) { this.importFromCatalogPanelFeeder.setNodeSourceWindowLabelWithError("Request sent to catalog failed", e); } }</code><technical_language>cases: slash</technical_language>

Target:
public void sendRequestToCatalog(String endpoint, RequestCallback callback) { RequestBuilder request = new RequestBuilder(RequestBuilder.GET, this.catalogUrl + "/" + endpoint); request.setHeader(CatalogConstants.SESSION_ID_PARAM, LoginModel.getInstance().getSessionId()); request.setCallback(callback); try { request.send(); } catch (RequestException e) { this.importFromCatalogPanelFeeder.setNodeSourceWindowLabelWithError("Request sent to catalog failed", e); } }
Source:
<code>private long roundToNextMinute(long timeInMillis) { Calendar calendar = <START> new GregorianCalendar(); <END> calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }</code><technical_language>this Calendar.getInstance() instead ? a no-op</technical_language>

Target:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }
Source:
<code>public Optional<ElderData> build(DataView container) throws InvalidDataException { if (container.contains(Keys.ELDER_GUARDIAN.getQuery())) { Optional<Boolean> elder = container.getBoolean(Keys.ELDER_GUARDIAN.getQuery()); <START> if (elder.isPresent()) { <END> return Optional.<ElderData>of(new SpongeElderData(elder.get())); } } return Optional.absent(); }</code><technical_language>checked if container contains query.... Also, contract is if container information build manipulator (or DataSerializable), throw InvalidDataException. kinda breaks contract here</technical_language>

Target:
public Optional<ElderData> build(DataView container) throws InvalidDataException { if(container.contains(Keys.ELDER_GUARDIAN.getQuery())) { return Optional.of(new SpongeElderData(DataUtil.getData(container, Keys.ELDER_GUARDIAN))); } return Optional.empty(); }
Source:
<code>public void info(String message, Object... objects) { <START> LOG.warn(message, objects); <END> }</code><technical_language>info warn</technical_language>

Target:
public void info(String message, Object... objects) { LOG.info(message, objects); }
Source:
<code>private EventHandler<ActiveContext> getSecondContextActiveHandlerForWorker() { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side ParameterWorker context - {0}", activeContext); final int workerIndex = Integer.parseInt(activeContext.getId().substring(WORKER_CONTEXT.length() + 1)); final Configuration taskConf = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, AsyncWorkerTask.TASK_ID_PREFIX + "-" + workerIndex) .set(TaskConfiguration.TASK, AsyncWorkerTask.class) .build(); final Configuration emIdConf = Tang.Factory.getTang().newConfigurationBuilder() <START> .bindImplementation(DataIdFactory.class, BaseCounterDataIdFactory.class).build(); <END> activeContext.submitTask(Configurations.merge(taskConf, workerConf, emIdConf)); } }; }</code><technical_language>BaseCounterDataIdFactory default implementation, remove this configuration</technical_language>

Target:
private EventHandler<ActiveContext> getSecondContextActiveHandlerForWorker() { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side ParameterWorker context - {0}", activeContext); final int workerIndex = Integer.parseInt(activeContext.getId().substring(WORKER_CONTEXT.length() + 1)); final Configuration taskConf = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, AsyncWorkerTask.TASK_ID_PREFIX + "-" + workerIndex) .set(TaskConfiguration.TASK, AsyncWorkerTask.class) .build(); final Configuration emDataIdConf = Tang.Factory.getTang().newConfigurationBuilder() .bindImplementation(DataIdFactory.class, BaseCounterDataIdFactory.class).build(); activeContext.submitTask(Configurations.merge(taskConf, workerConf, emDataIdConf)); } }; }