auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Entity<TreeReference> getEntity(TreeReference data) throws SessionUnavailableException { EvaluationContext nodeContext = new EvaluationContext(ec, data); Hashtable<String, XPathExpression> variables = getDetail().getVariableDeclarations(); for(Enumeration<String> en = variables.keys(); en.hasMoreElements();) { String key = en.nextElement(); nodeContext.setVariable(key, XPathFuncExpr.unpack(variables.get(key).eval(nodeContext))); } int length = detail.getHeaderForms().length; Object[] details = new Object[length]; String[] sortDetails = new String[length]; <START> String[] backgroundDetails = new String[detail.getHeaderForms().length]; <END> boolean[] relevancyDetails = new boolean[length]; int count = 0; for(DetailField f : this.getDetail().getFields()) { try { details[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); Text backgroundText = f.getBackground(); if(sortText == null) { sortDetails[count] = null; } else { sortDetails[count] = sortText.evaluate(nodeContext); } if(backgroundText == null) { backgroundDetails[count] = "no"; } else { backgroundDetails[count] = backgroundText.evaluate(nodeContext); } relevancyDetails[count] = f.isRelevant(nodeContext); } catch(XPathException xpe) { xpe.printStackTrace(); details[count] = "<invalid xpath: " + xpe.getMessage() + ">"; } catch (XPathSyntaxException e) { e.printStackTrace(); } count++; } return new Entity<TreeReference>(details, sortDetails, backgroundDetails, relevancyDetails, data); }</code><technical_language>I this is a weird merge effect, length here</technical_language>

Target:
public Entity<TreeReference> getEntity(TreeReference data) throws SessionUnavailableException { EvaluationContext nodeContext = new EvaluationContext(ec, data); Hashtable<String, XPathExpression> variables = getDetail().getVariableDeclarations(); for(Enumeration<String> en = variables.keys(); en.hasMoreElements();) { String key = en.nextElement(); nodeContext.setVariable(key, XPathFuncExpr.unpack(variables.get(key).eval(nodeContext))); } int length = detail.getHeaderForms().length; Object[] details = new Object[length]; String[] sortDetails = new String[length]; String[] backgroundDetails = new String[length]; boolean[] relevancyDetails = new boolean[length]; int count = 0; for(DetailField f : this.getDetail().getFields()) { try { details[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); Text backgroundText = f.getBackground(); if(sortText == null) { sortDetails[count] = null; } else { sortDetails[count] = sortText.evaluate(nodeContext); } if(backgroundText == null) { backgroundDetails[count] = ""; } else { backgroundDetails[count] = backgroundText.evaluate(nodeContext); } relevancyDetails[count] = f.isRelevant(nodeContext); } catch(XPathException xpe) { xpe.printStackTrace(); details[count] = "<invalid xpath: " + xpe.getMessage() + ">"; } catch (XPathSyntaxException e) { e.printStackTrace(); } count++; } return new Entity<TreeReference>(details, sortDetails, backgroundDetails, relevancyDetails, data); }
Source:
<code>public boolean equals(Object o) { if (!(o instanceof GeographyValue)) { return false; } GeographyValue that = (GeographyValue)o; if (this == that) { return true; } List<List<XYZPoint>> expectedLoops = that.m_loops; if (expectedLoops.size() != m_loops.size()) { return false; } Iterator<List<XYZPoint>> expectedLoopIt = expectedLoops.iterator(); for (List<XYZPoint> actualLoop : m_loops) { List<XYZPoint> expectedLoop = expectedLoopIt.next(); if (expectedLoop.size() != actualLoop.size()) { return false; }; Iterator<XYZPoint> expectedVertexIt = expectedLoop.iterator(); for (XYZPoint actualPt : actualLoop) { <START> XYZPoint expectedPt = expectedVertexIt.next(); <END> if (!expectedPt.equals(actualPt)) { return false; } } } return true; }</code><technical_language>XYZPoint.equals do? comparing polygon vertices, do do for comparing instances of GeographyPointValue, including considering points equal if some epsilon. convert instances of XYXPoint GeographyPointValue class's equals method</technical_language>

Target:
public boolean equals(Object o) { if (!(o instanceof GeographyValue)) { return false; } GeographyValue that = (GeographyValue)o; if (this == that) { return true; } List<List<GeographyPointValue>> expectedRings = that.getRings(); List<List<GeographyPointValue>> actualRings = getRings(); if (expectedRings.size() != actualRings.size()) { return false; } Iterator<List<GeographyPointValue>> expectedRingIt = expectedRings.iterator(); for (List<GeographyPointValue> actualRing : actualRings) { List<GeographyPointValue> expectedRing = expectedRingIt.next(); if (expectedRing.size() != actualRing.size()) { return false; }; Iterator<GeographyPointValue> expectedVertexIt = expectedRing.iterator(); for (GeographyPointValue actualPt : actualRing) { GeographyPointValue expectedPt = expectedVertexIt.next(); if (!expectedPt.equals(actualPt)) { return false; } } } return true; }
Source:
<code>public Object getAttribute(String name) { try { switch (name) { case JAVAX_SERVLET_REQUEST_X_509_CERTIFICATE: return SecureRequestCustomizer.this.getCertChain(_request, _session); case JAVAX_SERVLET_REQUEST_CIPHER_SUITE: return _session.getCipherSuite(); case JAVAX_SERVLET_REQUEST_KEY_SIZE: return SslContextFactory.deduceKeyLength(_session.getCipherSuite()); case JAVAX_SERVLET_REQUEST_SSL_SESSION_ID: return TypeUtil.toHexString(_session.getId()); default: String sessionAttribute = getSslSessionAttribute(); if (!StringUtil.isEmpty(sessionAttribute) && sessionAttribute.equals(name)) return _session; return _attributes.getAttribute(name); } } catch (Exception e) { <START> LOG.warn("Unable to customize request with encryption details", e); <END> return null; } }</code><technical_language>This is a copy/paste? message valid for this new wrapper version</technical_language>

Target:
public Object getAttribute(String name) { Object value = _attributes.getAttribute(name); if (value != null) return value; try { switch (name) { case JAVAX_SERVLET_REQUEST_X_509_CERTIFICATE: return SecureRequestCustomizer.this.getCertChain(_request, _session); case JAVAX_SERVLET_REQUEST_CIPHER_SUITE: return _session.getCipherSuite(); case JAVAX_SERVLET_REQUEST_KEY_SIZE: return SslContextFactory.deduceKeyLength(_session.getCipherSuite()); case JAVAX_SERVLET_REQUEST_SSL_SESSION_ID: return TypeUtil.toHexString(_session.getId()); default: String sessionAttribute = getSslSessionAttribute(); if (!StringUtil.isEmpty(sessionAttribute) && sessionAttribute.equals(name)) return _session; } } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("Unable to get secure details ", e); } return null; }
Source:
<code>public void setUp() { syncedPatientsPresenter = new SyncedPatientsPresenter(view, patientDAO); patientList = new ArrayList<>(); Patient patient1 = createPatient(1L); <START> patient1.getPerson().getName().setGivenName("TEST"); <END> Patient patient2 = createPatient(2L); patient1.getPerson().getName().setGivenName("TEST1"); Patient patient3 = createPatient(3L); patient1.getPerson().getName().setGivenName("TEST11"); patientList.add(patient1); patientList.add(patient2); patientList.add(patient3); }</code><technical_language>changing createPatient() set name based id passed this method "patient_{id}"? This reuse this :)</technical_language>

Target:
public void setUp() { super.setUp(); syncedPatientsPresenter = new SyncedPatientsPresenter(view, patientDAO); patientList = new ArrayList<>(); patientList.add(createPatient(1L)); patientList.add(createPatient(2L)); patientList.add(createPatient(3L)); }
Source:
<code>public void testConvert() { <START> List<VariantSourceMongo> variantSourceMongos = new ArrayList<>(); <END> String fileId = "fileId"; String fileName = "fileName"; String studyId = "studyId"; String studyName = "studyName"; StudyType type = StudyType.CONTROL; Aggregation aggregation = Aggregation.NONE; Date date = new Date(1); Map<String, Integer> samplesPosition = new HashMap<>(); Map<String, Object> metadata = new HashMap<>(); VariantGlobalStatsMongo stats = new VariantGlobalStatsMongo(1, 1, 1, 0, 0, 1, 1, 0, 1); VariantSourceMongo variantSourceMongo = new VariantSourceMongo(fileId, fileName, studyId, studyName, type, aggregation, samplesPosition, metadata, stats); VariantSource variantSource = new VariantSource(fileId, fileName, studyId, studyName, type, aggregation, date, samplesPosition, metadata, stats); variantSourceMongo.setDate(variantSource.getDate()); variantSourceMongos.add(variantSourceMongo); List<VariantSource> variantSources = service.convert(variantSourceMongos); assertEquals(variantSource, variantSources.get(0)); }</code><technical_language>Initialize this variable closer usage</technical_language>

Target:
public void testConvert() { String fileId = "fileId"; String fileName = "fileName"; String studyId = "studyId"; String studyName = "studyName"; StudyType type = StudyType.CONTROL; Aggregation aggregation = Aggregation.NONE; Date date = new Date(1); Map<String, Integer> samplesPosition = new HashMap<>(); Map<String, Object> metadata = new HashMap<>(); VariantGlobalStatsMongo stats = new VariantGlobalStatsMongo(1, 1, 1, 0, 0, 1, 1, 0, 1); VariantSourceMongo variantSourceMongo = new VariantSourceMongo(fileId, fileName, studyId, studyName, type, aggregation, samplesPosition, metadata, stats); VariantSource variantSource = new VariantSource(fileId, fileName, studyId, studyName, type, aggregation, date, samplesPosition, metadata, stats); variantSourceMongo.setDate(variantSource.getDate()); List<VariantSourceMongo> variantSourceMongos = new ArrayList<>(); variantSourceMongos.add(variantSourceMongo); List<VariantSource> variantSources = service.convert(variantSourceMongos); assertEquals(variantSource, variantSources.get(0)); }
Source:
<code>public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { <START> throw new IllegalStateException("parameterDefinitionName is null"); <END> } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }</code><technical_language>I throw IllegalArgumentException</technical_language>

Target:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { throw new IllegalArgumentException("parameterDefinitionName is null"); } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }
Source:
<code>private void createBulkNewBranchMenuItem(Menu menu, final Repository[] repositories) { MenuItem newBranch = getNewBranchMenuItem(menu); newBranch.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { InputDialog dialog = new InputDialog(e.display.getActiveShell(), UIText.CreateBranchBulkDialog_Title, UIText.CreateBranchBulkDialog_Description, "", new IInputValidator() { @Override public String isValid(String newBranchName) { return validateNewBulkBranchName(newBranchName, repositories); } <START> }); <END> if (dialog.open() == Window.OK) { String name = dialog.getValue(); try { for (Repository repository : repositories) { Ref headRef = repository.exactRef(Constants.HEAD); if (headRef != null) { ObjectId headId = headRef.getLeaf() .getObjectId(); RevCommit head = repository.parseCommit(headId); CreateLocalBranchOperation op = new CreateLocalBranchOperation( repository, name, head); op.execute(null); } } BranchOperationUI.checkout(repositories, name).start(); } catch (Exception exception) { Activator.handleError( UIText.CreateBranchBulkDialog_Error, exception, true); } } } }); }</code><technical_language>I add a BranchNameNormalizer Text widget here</technical_language>

Target:
private void createBulkNewBranchMenuItem(Menu menu, final Repository[] repositories) { MenuItem newBranch = getNewBranchMenuItem(menu); newBranch.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { InputDialog dialog = new InputDialog(e.display.getActiveShell(), UIText.CreateBranchBulkDialog_Title, UIText.CreateBranchBulkDialog_Description, "", new IInputValidator() { @Override public String isValid(String newBranchName) { return validateNewBulkBranchName(newBranchName, repositories); } }) { @Override protected Control createDialogArea(Composite parent) { Control result = super.createDialogArea(parent); BranchNameNormalizer normalizer = new BranchNameNormalizer( getText()); normalizer.setVisible(false); return result; } }; if (dialog.open() == Window.OK) { String name = dialog.getValue(); try { for (Repository repository : repositories) { Ref headRef = repository.exactRef(Constants.HEAD); if (headRef != null) { ObjectId headId = headRef.getLeaf() .getObjectId(); RevCommit head = repository.parseCommit(headId); CreateLocalBranchOperation op = new CreateLocalBranchOperation( repository, name, head); op.execute(null); } } BranchOperationUI.checkout(repositories, name).start(); } catch (Exception exception) { Activator.handleError( UIText.CreateBranchBulkDialog_Error, exception, true); } } } }); }
Source:
<code>public DatacenterBrokerBestFit(final CloudSim simulation) { super(simulation); <START> setVmMapper(this::defaultVmMapper); <END> this.vmNumberOfPesUpdated = new HashMap<>(); firstVmMapperCall = true; }</code><technical_language>checked if this line is necessary? superclass calls setVmMapper. I suppose required this subclass overridden defaultVmMapper</technical_language>

Target:
public DatacenterBrokerBestFit(final CloudSim simulation) { super(simulation); }
Source:
<code><START> public <T extends BasePage> Console waitForFirstNavigationPanel(Class<T> clazz) { <END> browser.navigate().refresh(); Graphene.goTo(HomePage.class); waitUntilLoaded(); Graphene.goTo(clazz); waitUntilLoaded().maximizeWindow(); Graphene.waitModel().until().element(By.className("navigation-column")).is().visible(); return this; }</code><technical_language>this method call refreshAndNavigate wait? avoid code duplication increase readability</technical_language>

Target:
public <T extends BasePage> Console waitForFirstNavigationPanel(Class<T> clazz) { refreshAndNavigate(clazz); Graphene.waitModel().until().element(By.className("navigation-column")).is().visible(); return this; }
Source:
<code>private String generatejar(String pojoClassName) throws IOException, InterruptedException { String sourceDir = "src/test/resources/dynamicJar/"; String destDir = testMeta.getPath(); String version = getJavaSrcVersion(); Process p = Runtime.getRuntime() <START> .exec(new String[] {"javac", "-source", version, "-target", version, "-d", destDir, sourceDir + pojoClassName + ".java"}, null, null); <END> IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); p = Runtime.getRuntime() .exec(new String[] {"jar", "-cf", pojoClassName + ".jar", pojoClassName + ".class"}, null, new File(destDir)); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); return new File(destDir, pojoClassName + ".jar").getAbsolutePath(); }</code><technical_language>works if "javac" PATH is version run unit tests. is case version of javac PATH 1.6 1.7. Instead of external "javac" rely JavaCompiler</technical_language>

Target:
private String generatejar(String pojoClassName) throws IOException, InterruptedException { String sourceDir = "src/test/resources/dynamicJar/"; String destDir = testMeta.getPath(); String binLocation = getJavaBinLocation(); Process p = Runtime.getRuntime() .exec(new String[] {binLocation + "javac", "-d", destDir, sourceDir + pojoClassName + ".java"}, null, null); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); p = Runtime.getRuntime() .exec(new String[] {binLocation + "jar", "-cf", pojoClassName + ".jar", pojoClassName + ".class"}, null, new File(destDir)); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); return new File(destDir, pojoClassName + ".jar").getAbsolutePath(); }
Source:
<code>public static ColumnValueSelector makeColumnValueSelector( ColumnSelectorFactory columnSelectorFactory, Expr expression ) { final ColumnValueSelector<ExprEval> baseSelector = makeExprEvalSelector(columnSelectorFactory, expression); return new ColumnValueSelector() { @Override public double getDouble() { <START> return baseSelector.getDouble(); <END> } @Override public boolean isNull() { return baseSelector.getObject().isNull(); } @Override public float getFloat() { return baseSelector.getFloat(); } @Override public long getLong() { return baseSelector.getLong(); } @Nullable @Override public Object getObject() { return baseSelector.getObject().value(); } @Override public Class classOfObject() { return Object.class; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } }; }</code><technical_language>checks</technical_language>

Target:
public static ColumnValueSelector makeColumnValueSelector( ColumnSelectorFactory columnSelectorFactory, Expr expression ) { final ColumnValueSelector<ExprEval> baseSelector = makeExprEvalSelector(columnSelectorFactory, expression); return new ColumnValueSelector() { @Override public double getDouble() { return baseSelector.getDouble(); } @Override public float getFloat() { return baseSelector.getFloat(); } @Override public long getLong() { return baseSelector.getLong(); } @Override public boolean isNull() { return baseSelector.isNull(); } @Nullable @Override public Object getObject() { return baseSelector.getObject().value(); } @Override public Class classOfObject() { return Object.class; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } }; }
Source:
<code>private void closeNewWindows(WebDriver webDriver, String currentWindowHandle, Set<String> currentWindows) { Set<String> windowHandles = webDriver.getWindowHandles(); if (windowHandles.size() != currentWindows.size()) { Set<String> newWindows = new HashSet<>(windowHandles); newWindows.removeAll(currentWindows); log.info("File has been opened in a new window, let's close new windows", newWindows.size()); for (String newWindow : newWindows) { log.info(" Let's close {}", newWindow); try { webDriver.switchTo().window(newWindow); webDriver.close(); } catch (NoSuchWindowException windowHasBeenClosedMeanwhile) { log.info(" Failed to close {}: {}", newWindow, Cleanup.of.webdriverExceptionMessage(windowHasBeenClosedMeanwhile)); } catch (Exception e) { <START> log.warn(" Failed to close " + newWindow + ": " + e); <END> } } webDriver.switchTo().window(currentWindowHandle); } }</code><technical_language>Format</technical_language>

Target:
private void closeNewWindows(WebDriver webDriver, String currentWindowHandle, Set<String> currentWindows) { Set<String> windowHandles = webDriver.getWindowHandles(); if (windowHandles.size() != currentWindows.size()) { Set<String> newWindows = new HashSet<>(windowHandles); newWindows.removeAll(currentWindows); log.info("File has been opened in a new window, let's close new windows", newWindows.size()); for (String newWindow : newWindows) { log.info(" Let's close {}", newWindow); try { webDriver.switchTo().window(newWindow); webDriver.close(); } catch (NoSuchWindowException windowHasBeenClosedMeanwhile) { log.info(" Failed to close {}: {}", newWindow, Cleanup.of.webdriverExceptionMessage(windowHasBeenClosedMeanwhile)); } catch (Exception e) { log.warn(" Failed to close {}", newWindow, e); } } webDriver.switchTo().window(currentWindowHandle); } }
Source:
<code>public RichMember call(ApiCaller ac, Deserializer params) throws PerunException { ac.stateChangingCheck(); String password = params.readString("password"); Vo vo = ac.getVoById(params.readInt("vo")); String namespace = params.readString("namespace"); User sponsor = null; if(params.contains("sponsor")) { sponsor = ac.getUserById(params.readInt("sponsor")); } Map<String, String> name = new HashMap<>(); <START> if (params.contains("firstName")) { <END> name.put("firstName", params.readString("firstName")); name.put("lastName", params.readString("lastName")); if (params.contains("titleBefore")) name.put("titleBefore", params.readString("titleBefore")); if (params.contains("titleAfter")) name.put("titleAfter", params.readString("titleAfter")); } else { name.put("guestName", params.readString("guestName")); } return ac.getMembersManager().createSponsoredMember(ac.getSession(), vo, namespace, name, password, sponsor); }</code><technical_language>I prefer differentiate behavior based presence of guestName firstName. is this in BL logic conforms original implementation. this pass guestName lastName work lastName letting know. create branch throw exception if wrong combination of params is passed. Like: java if (params.contains("guestName")) { ... } else if (params.contains("firstName") && params.contains("lastName")) { ... } else { throw new Exception() }</technical_language>

Target:
public RichMember call(ApiCaller ac, Deserializer params) throws PerunException { ac.stateChangingCheck(); String password = params.readString("password"); Vo vo = ac.getVoById(params.readInt("vo")); String namespace = params.readString("namespace"); User sponsor = null; if(params.contains("sponsor")) { sponsor = ac.getUserById(params.readInt("sponsor")); } Map<String, String> name = new HashMap<>(); if (params.contains("guestName")) { name.put("guestName", params.readString("guestName")); } else if (params.contains("firstName") && params.contains("lastName")) { name.put("firstName", params.readString("firstName")); name.put("lastName", params.readString("lastName")); if (params.contains("titleBefore")) name.put("titleBefore", params.readString("titleBefore")); if (params.contains("titleAfter")) name.put("titleAfter", params.readString("titleAfter")); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "Missing value. Either 'guestName' or ('firstName' and 'lastName') must be sent."); } return ac.getMembersManager().createSponsoredMember(ac.getSession(), vo, namespace, name, password, sponsor); }
Source:
<code>public void popUp(SessionDataDto sessionDataDto, String userComment, SessionComparisonPanel.TreeItem item) { <START> getApplyButton().removeFromParent(); <END> currentTreeItem = item; currentSessionDataDto = sessionDataDto; setText("Session " + sessionDataDto.getSessionId()); textArea.setText(userComment); onTextAreaContentChanged(); show(); textArea.setFocus(true); }</code><technical_language>necessary implement now, IMHO more convenient buttons AbstractWindow need instead of removing unused buttons</technical_language>

Target:
public void popUp(SessionDataDto sessionDataDto, String userComment, SessionComparisonPanel.TreeItem item) { if (sessionDataDto==null){ new ExceptionPanel("The session data has a value null. The session's id is wrong."); } getApplyButton().removeFromParent(); currentTreeItem = item; currentSessionDataDto = sessionDataDto; setText("Session " + sessionDataDto.getSessionId()); textArea.setText(userComment); onTextAreaContentChanged(); show(); textArea.setFocus(true); }
Source:
<code>public void shouldSetMd5AndSSLPortHeaders() throws Exception { ServerBinaryDownloader downloader = new ServerBinaryDownloader(ServerUrlGeneratorMother.generatorFor("localhost", 9090), null, SslVerificationMode.NONE); downloader.downloadIfNecessary(DownloadableFile.AGENT); <START> assertThat(downloader.getMd5(), is(md5DigestOfStream(new FileInputStream(DownloadableFile.AGENT.getLocalFile())))); <END> assertThat(downloader.getSslPort(), is("9091")); }</code><technical_language>Close this stream</technical_language>

Target:
public void shouldSetMd5AndSSLPortHeaders() throws Exception { ServerBinaryDownloader downloader = new ServerBinaryDownloader(ServerUrlGeneratorMother.generatorFor("localhost", 9090), null, SslVerificationMode.NONE); downloader.downloadIfNecessary(DownloadableFile.AGENT); try(BufferedInputStream stream = new BufferedInputStream(new FileInputStream(DownloadableFile.AGENT.getLocalFile()))) { assertThat(downloader.getMd5(), is(md5DigestOfStream(stream))); } assertThat(downloader.getSslPort(), is("9091")); }
Source:
<code>public Set<String> getSourceIds() { <START> return audioSources.keySet(); <END> }</code><technical_language>keySet is a view... So, caller run a CME returned Set Map changes. return a new set created content of view set</technical_language>

Target:
public Set<String> getSourceIds() { return new HashSet<>(audioSources.keySet()); }
Source:
<code>protected void onPostExecute(String response) { String decodedString = ""; Log.d("WOOTRIC_SDK", "response: " + response); try { decodedString = new String(response.getBytes("ISO-8859-1"), "UTF-8"); onSuccess(decodedString); } catch (UnsupportedEncodingException e) { onSuccess(response); <START> } catch (NullPointerException e) { <END> onSuccess(response); } }</code><technical_language>good. exception other Unsupported NPE? If for it. In talking @hachibu , process is other dev review PR creator merge proceed now</technical_language>

Target:
protected void onPostExecute(String response) { String decodedString = ""; Log.d("WOOTRIC_SDK", "response: " + response); if (response != null) { try { decodedString = new String(response.getBytes("ISO-8859-1"), "UTF-8"); onSuccess(decodedString); } catch (UnsupportedEncodingException e) { onSuccess(response); } } }
Source:
<code>public void shutdown() throws IOException { if ( index != null ) { <START> index.close(); <END> } }</code><technical_language>opportunity set index = null here</technical_language>

Target:
public void shutdown() throws IOException { if ( index != null ) { index.close(); index = null; } }
Source:
<code>private ServiceAccount findService(HttpServletRequest request) throws IOException { String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (StringUtils.isEmpty(authorizationHeader)) { warn().log("service auth header is empty returning null"); return null; } authorizationHeader = authorizationHeader.toLowerCase(); if (!authorizationHeader.startsWith("bearer ")) { warn().log("authorization header does not begin with the required bearer prefix returning null"); return null; } String serviceToken = removeBearerPrefix(authorizationHeader); ServiceAccount serviceAccount = null; try { <START> serviceAccount = getServiceStore().get(serviceToken); <END> } catch (IOException ex) { error().exception(ex).log("unexpected error getting service account"); throw ex; } if (serviceAccount == null) { warn().log("service account not found"); return null; } info().log("identified valid service account"); return serviceAccount; }</code><technical_language>line 106 lowercasing auth header service token lowercased. service store service endpoint enforcing token lowercased there. this is a direct lookup want explicit lowercasing everywhere. Potentially add this ServiceStoreImpl</technical_language>

Target:
private ServiceAccount findService(HttpServletRequest request) throws IOException { info().log("identity: handling service identity request"); String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (!isValidAuthorizationHeader(authorizationHeader)) { return null; } String serviceToken = removeBearerPrefix(authorizationHeader); ServiceAccount serviceAccount = null; try { serviceAccount = serviceStore.get(serviceToken); } catch (Exception ex) { error().exception(ex).log("unexpected error getting service account"); throw new IOException(ex); } if (serviceAccount == null) { warn().log("service account not found for service token"); return null; } info().data("service_id", serviceAccount.getID()).log("identified valid service account"); return serviceAccount; }
Source:
<code>private void testNoSupportForIterationsInBatchHelper(final Transformation<?>... transformations) { final List<Transformation<?>> registeredTransformations = new ArrayList<>(); Collections.addAll(registeredTransformations, transformations); StreamGraphGenerator streamGraphGenerator = new StreamGraphGenerator( registeredTransformations, new ExecutionConfig(), new CheckpointConfig()); <START> streamGraphGenerator.setRuntimeExecutionMode(RuntimeExecutionMode.AUTOMATIC); <END> expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Iterations are not supported in BATCH execution mode."); streamGraphGenerator.generate(); }</code><technical_language>set BATCH more specific in test</technical_language>

Target:
private void testNoSupportForIterationsInBatchHelper(final Transformation<?>... transformations) { final List<Transformation<?>> registeredTransformations = new ArrayList<>(); Collections.addAll(registeredTransformations, transformations); StreamGraphGenerator streamGraphGenerator = new StreamGraphGenerator( registeredTransformations, new ExecutionConfig(), new CheckpointConfig()); streamGraphGenerator.setRuntimeExecutionMode(RuntimeExecutionMode.BATCH); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Iterations are not supported in BATCH execution mode."); streamGraphGenerator.generate(); }
Source:
<code>public void runTask() { int dispatched = 0; for (final Message message : MessagingSystem.getInstance().getMessagePendingDispatchSet()) { long start = System.currentTimeMillis(); MessageDispatchReport report = MessagingSystem.dispatch(message); getLogger().info("Dispatched message: in {}ms for emails", message.getExternalId(), System.currentTimeMillis() - start, report.getTotalCount()); dispatched++; } taskLog("Dispatched %d messages\n", dispatched); <START> MessagingSystem.deleteOldMessages(); <END> }</code><technical_language>Why</technical_language>

Target:
public void runTask() { MessagingSystem.deleteOldMessages(); int dispatched = 0; for (final Message message : MessagingSystem.getInstance().getMessagePendingDispatchSet()) { long start = System.currentTimeMillis(); MessageDispatchReport report = MessagingSystem.dispatch(message); getLogger().info("Dispatched message: in {}ms for emails", message.getExternalId(), System.currentTimeMillis() - start, report.getTotalCount()); dispatched++; } taskLog("Dispatched %d messages\n", dispatched); }
Source:
<code>public Set<DiscoveryDruidNode> getAllNodes() { <START> return new ImmutableSet.Builder().addAll(nodes.values()).build(); <END> }</code><technical_language>this need a copy, Collections.immutableSet() enough</technical_language>

Target:
public Collection<DiscoveryDruidNode> getAllNodes() { return Collections.unmodifiableCollection(nodes.values()); }
Source:
<code><START> protected static int parseSquashFixupSequenceCount(String currSquashMessage) { <END> String regex = "This is a combination of (.*) commits"; String firstLine = currSquashMessage.substring(0, currSquashMessage.indexOf("\n")); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(firstLine); if (!matcher.find()) throw new IllegalArgumentException(); return Integer.parseInt(matcher.group(1)); }</code><technical_language>Please remove protected keyword this class subclassed</technical_language>

Target:
static int parseSquashFixupSequenceCount(String currSquashMessage) { String regex = "This is a combination of (.*) commits"; String firstLine = currSquashMessage.substring(0, currSquashMessage.indexOf("\n")); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(firstLine); if (!matcher.find()) throw new IllegalArgumentException(); return Integer.parseInt(matcher.group(1)); }
Source:
<code>public ForkingTaskRunner( ForkingTaskRunnerConfig config, TaskConfig taskConfig, WorkerConfig workerConfig, Properties props, TaskLogPusher taskLogPusher, ObjectMapper jsonMapper, @Self DruidNode node ) { this.config = config; this.taskConfig = taskConfig; this.props = props; this.taskLogPusher = taskLogPusher; this.jsonMapper = jsonMapper; this.node = node; this.portFinder = new PortFinder(config.getStartPort()); this.exec = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( workerConfig.getCapacity(), <START> new ThreadFactoryBuilder() <END> .setNameFormat("forking-task-runner-%d") .setDaemon(true) .build() ) ); }</code><technical_language>io.druid.concurrent.Execs#makeThreadFactory</technical_language>

Target:
public ForkingTaskRunner( ForkingTaskRunnerConfig config, TaskConfig taskConfig, WorkerConfig workerConfig, Properties props, TaskLogPusher taskLogPusher, ObjectMapper jsonMapper, @Self DruidNode node ) { this.config = config; this.taskConfig = taskConfig; this.props = props; this.taskLogPusher = taskLogPusher; this.jsonMapper = jsonMapper; this.node = node; this.portFinder = new PortFinder(config.getStartPort()); this.exec = MoreExecutors.listeningDecorator( Execs.multiThreaded(workerConfig.getCapacity(), "forking-task-runner-%d") ); }
Source:
<code>@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughTraits( final RelTraitSet required) { RelCollation collation = required.getCollation(); if (collation == null || collation == RelCollations.EMPTY) { return null; } List<Integer> requiredKeys = RelCollations.ordinals(collation); ImmutableBitSet requiredKeySet = ImmutableBitSet.of(requiredKeys); ImmutableBitSet leftKeySet = ImmutableBitSet.of(joinInfo.leftKeys); ImmutableBitSet rightKeySet = ImmutableBitSet.of(joinInfo.rightKeys) .shift(left.getRowType().getFieldCount()); <START> if (joinType == JoinRelType.LEFT) { <END> if (requiredKeySet.equals(leftKeySet)) { return Pair.of( required, ImmutableList.of( required, required.replace(RelCollations.EMPTY))); } } else if (joinType == JoinRelType.RIGHT) { if (requiredKeySet.equals(rightKeySet)) { RelCollation rightCollation = RelCollations.shift(collation, -left.getRowType().getFieldCount()); return Pair.of( required, ImmutableList.of( required.replace(RelCollations.EMPTY), required.replace(rightCollation))); } } return null; }</code><technical_language>join, SEMI/ANTI SEMI, LEFT pass request left child, derive left child</technical_language>

Target:
@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughTraits( final RelTraitSet required) { RelCollation collation = required.getCollation(); if (collation == null || collation == RelCollations.EMPTY || joinType == JoinRelType.FULL || joinType == JoinRelType.RIGHT) { return null; } for (RelFieldCollation fc : collation.getFieldCollations()) { if (fc.getFieldIndex() >= getLeft().getRowType().getFieldCount()) { return null; } } RelTraitSet passthroughTraitSet = traitSet.replace(collation); return Pair.of(passthroughTraitSet, ImmutableList.of( passthroughTraitSet, passthroughTraitSet.replace(RelCollations.EMPTY))); }
Source:
<code>public void testObjectConstruction() { ClassObj clazz = mState.findClass("java.lang.Thread$State"); assertNotNull(clazz); Object object = clazz.getStaticField(Type.OBJECT, <START> "$VALUES").getValue(); <END> assertTrue(object instanceof ArrayInstance); ArrayInstance array = (ArrayInstance) object; Value[] values = array.getValues(); assertEquals(6, values.length); Collection<Instance> instances = clazz.getInstances(); for (Value value : values) { assertTrue(value.getValue() instanceof Instance); assertTrue(instances.contains(value.getValue())); } Object blocked = clazz.getStaticField(Type.OBJECT, "NEW").getValue(); assertTrue(blocked instanceof ClassInstance); ClassInstance instance = (ClassInstance) blocked; assertSame(clazz, instance.getClassObj()); Object name = instance.getField(Type.OBJECT, "name").getValue(); assertTrue(name instanceof ClassInstance); ClassInstance string = (ClassInstance) name; assertEquals("java.lang.String", string.getClassObj().getClassName()); Object value = string.getField(Type.OBJECT, "value").getValue(); assertTrue(value instanceof ArrayInstance); Value[] data = ((ArrayInstance) value).getValues(); assertEquals(3, data.length); assertEquals('N', data[0].getValue()); assertEquals('E', data[1].getValue()); assertEquals('W', data[2].getValue()); Object ordinal = instance.getField(Type.INT, "ordinal").getValue(); assertEquals(0, ordinal); }</code><technical_language>JVM details ignoramus here: Is a commonly $VALUES of Enum is equivalent values() method</technical_language>

Target:
public void testObjectConstruction() { ClassObj clazz = mState.findClass("java.lang.Thread$State"); assertNotNull(clazz); Object object = clazz.getStaticField(Type.OBJECT, "$VALUES").getValue(); assertTrue(object instanceof ArrayInstance); ArrayInstance array = (ArrayInstance) object; Value[] values = array.getValues(); assertEquals(6, values.length); Collection<Instance> instances = clazz.getInstances(); for (Value value : values) { assertTrue(value.getValue() instanceof Instance); assertTrue(instances.contains(value.getValue())); } Object enumValue = clazz.getStaticField(Type.OBJECT, "NEW").getValue(); assertTrue(enumValue instanceof ClassInstance); ClassInstance instance = (ClassInstance) enumValue; assertSame(clazz, instance.getClassObj()); Object name = instance.getField(Type.OBJECT, "name").getValue(); assertTrue(name instanceof ClassInstance); ClassInstance string = (ClassInstance) name; assertEquals("java.lang.String", string.getClassObj().getClassName()); Object value = string.getField(Type.OBJECT, "value").getValue(); assertTrue(value instanceof ArrayInstance); Value[] data = ((ArrayInstance) value).getValues(); assertEquals(3, data.length); assertEquals('N', data[0].getValue()); assertEquals('E', data[1].getValue()); assertEquals('W', data[2].getValue()); Object ordinal = instance.getField(Type.INT, "ordinal").getValue(); assertEquals(0, ordinal); }
Source:
<code>public Result doWork() { final boolean isImmediate = getInputData() != null ? getInputData().getBoolean(PARAM_RUN_IMMEDIATE, false) : false; Log.d(TAG, "doWork() : isImmediate = " + isImmediate); ClientConfig.initialize(getApplicationContext()); <START> <END> AtomicBoolean finished = new AtomicBoolean(false); if (NetworkUtils.networkAvailable() && NetworkUtils.isFeedRefreshAllowed()) { DBTasks.refreshAllFeeds(getApplicationContext(), null, () -> finished.set(true)); } else { Log.d(TAG, "Blocking automatic update: no wifi available / no mobile updates allowed"); } Awaitility.await().until(finished::get); if (!isImmediate && UserPreferences.isAutoUpdateTimeOfDay()) { UserPreferences.restartUpdateAlarm(); } return Result.success(); }</code><technical_language>This create a deadlock AtomicBoolean is updated. Moving await().until part if help</technical_language>

Target:
public Result doWork() { final boolean isRunOnce = getInputData().getBoolean(PARAM_RUN_ONCE, false); Log.d(TAG, "doWork() : isRunOnce = " + isRunOnce); ClientConfig.initialize(getApplicationContext()); if (NetworkUtils.networkAvailable() && NetworkUtils.isFeedRefreshAllowed()) { DBTasks.refreshAllFeeds(getApplicationContext()); } else { Log.d(TAG, "Blocking automatic update: no wifi available / no mobile updates allowed"); } if (!isRunOnce && UserPreferences.isAutoUpdateTimeOfDay()) { AutoUpdateManager.restartUpdateAlarm(); } return Result.success(); }
Source:
<code>private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); <START> final long now = SystemReader.getInstance().getCurrentTime(); <END> final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }</code><technical_language>a simple System.currrentTimeMillis() instead of SystemReader</technical_language>

Target:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); final long now = System.currentTimeMillis(); final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }
Source:
<code>public void testUnsubscription() { final AtomicBoolean wasCalled = new AtomicBoolean(false); PublishSubject<Integer> source = PublishSubject.create(); Subscription subscription = source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).take(3).subscribe(); assertTrue(source.hasObservers()); source.onNext(0); source.onNext(1); assertTrue(source.hasObservers()); source.onNext(2); <START> assertTrue(!source.hasObservers()); <END> subscription.unsubscribe(); assertTrue(!wasCalled.get()); }</code><technical_language>Please assertFalse</technical_language>

Target:
public void testUnsubscription() { final AtomicBoolean wasCalled = new AtomicBoolean(false); PublishSubject<Integer> source = PublishSubject.create(); Subscription subscription = source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).take(3).subscribe(); assertTrue(source.hasObservers()); source.onNext(0); source.onNext(1); assertTrue(source.hasObservers()); source.onNext(2); assertFalse(source.hasObservers()); subscription.unsubscribe(); assertFalse(wasCalled.get()); }
Source:
<code>private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); <START> if (status < 200 || status > 300) { <END> return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }</code><technical_language>if status is 300? check bestatus >= 300</technical_language>

Target:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }
Source:
<code>public String toString() { <START> return String.format("SMALL_RECT[%s,%s,%s,%s]", Left, Top, Right, Bottom); <END> }</code><technical_language>offering suggestions</technical_language>

Target:
public String toString() { return String.format("SMALL_RECT(%s,%s)(%s,%s)", Left, Top, Right, Bottom); }
Source:
<code>public byte[] encode(final LinearModel model) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(getNumBytes(model)); <START> final DataOutputStream dos = new DataOutputStream(baos); <END> encodeToStream(model, dos); return baos.toByteArray(); }</code><technical_language>closing DataOutputStream. Check SparseVectorCodec too</technical_language>

Target:
public byte[] encode(final LinearModel model) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(getNumBytes(model)); final DataOutputStream dos = new DataOutputStream(baos)) { encodeToStream(model, dos); return baos.toByteArray(); } catch (final IOException e) { throw new RuntimeException(e.getCause()); } }
Source:
<code>public static Flag valueOf(String internalName) throws IllegalArgumentException { try { <START> return (Flag)(Flag.class.getField(internalName).get(null)); <END> } catch (NoSuchFieldException e) { if (internalName.startsWith(USER_PREFIX)) { return Flag.createFlag(internalName.substring(USER_PREFIX.length())); } else { return Flag.createFlag(internalName); } } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } }</code><technical_language>reflection here, I extract internal flags listed in valueOfByRealName a method returning a set of Strings if contains internalName. ensure new method is in sync actual fields in a unit test.The unit test reflection enumerate Flag's fields concern performance</technical_language>

Target:
public static Flag valueOf(String internalName) throws IllegalArgumentException { for (Flag f : KNOWN_FLAGS) { if (f.mName.equalsIgnoreCase(internalName)) { return f; } } if (internalName.startsWith(USER_PREFIX)) { return Flag.createFlag(internalName.substring(USER_PREFIX.length())); } else { return Flag.createFlag(internalName); } }
Source:
<code>public GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields) { super( checkNotNull(name, "name"), checkNotNull(repetition, "repetition"), originalType ); <START> checkNotNull(fields, "fields"); <END> this.fields = fields; this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }</code><technical_language>this.fields = checkNotNull(fields, "fields");</technical_language>

Target:
public GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields) { super( checkNotNull(name, "name"), checkNotNull(repetition, "repetition"), originalType ); this.fields = checkNotNull(fields, "fields"); this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }
Source:
<code>public TmfCoalescedEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { super(ITmfEvent.class, null, index, nbRequested, priority); <START> fRange = range; <END> }</code><technical_language>add trace (TmfCoreTracer)</technical_language>

Target:
public TmfCoalescedEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { super(ITmfEvent.class, null, index, nbRequested, priority); fRange = range; if (TmfCoreTracer.isRequestTraced()) { String type = getClass().getName(); type = type.substring(type.lastIndexOf('.') + 1); @SuppressWarnings("nls") String message = "CREATED " + (getExecType() == ITmfEventRequest.ExecutionType.BACKGROUND ? "(BG)" : "(FG)") + " Type=" + type + " Index=" + getIndex() + " NbReq=" + getNbRequested() + " Range=" + getRange() + " DataType=" + getDataType().getSimpleName(); TmfCoreTracer.traceRequest(this, message); } }
Source:
<code>public TopNNumericResultBuilder( DateTime timestamp, DimensionSpec dimSpec, String metricName, int threshold, final Comparator comparator, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { this.timestamp = timestamp; this.dimSpec = dimSpec; this.metricName = metricName; this.aggFactories = aggFactories; this.postAggs = AggregatorUtil.pruneDependentPostAgg(postAggs, this.metricName); this.threshold = threshold; this.metricComparator = comparator; this.dimNameComparator = new Comparator<String>() { @Override <START> public int compare(String o1, String o2) <END> { int retval; if (o1 == null) { retval = -1; } else if (o2 == null) { retval = 1; } else { retval = o1.compareTo(o2); } return retval; } }; this.dimValComparator = new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } }; pQueue = new PriorityQueue<>(this.threshold + 1, this.dimValComparator); }</code><technical_language>handle case o1 == o2 == null</technical_language>

Target:
public TopNNumericResultBuilder( DateTime timestamp, DimensionSpec dimSpec, String metricName, int threshold, final Comparator comparator, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { this.timestamp = timestamp; this.dimSpec = dimSpec; this.metricName = metricName; this.aggFactories = aggFactories; this.postAggs = AggregatorUtil.pruneDependentPostAgg(postAggs, this.metricName); this.threshold = threshold; this.metricComparator = comparator; this.dimValComparator = new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } }; pQueue = new PriorityQueue<>(this.threshold + 1, this.dimValComparator); }