auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getSignatureInFormat(final ScriptType scriptType, final String signStr, final String certStr, String messageDigestAlgo, String provider) throws ScriptSignatureException { if ((scriptType == null) || (signStr == null) || signStr.isEmpty() || (certStr == null) || certStr.isEmpty()) throw new ScriptSignatureException("One or more parameters are null or empty"); if ((messageDigestAlgo == null) || messageDigestAlgo.isEmpty() || "default".equalsIgnoreCase(messageDigestAlgo)) messageDigestAlgo = DEFAULT_MESSAGE_DIGEST_ALGO; if ((provider == null) || provider.isEmpty()) provider = DEFAULT_SIGNATURE_PROVIDER; final String LINE_DELIMETER = AbstractCodeFactory.LINE_DELIMITER; final String begin = LINE_DELIMETER + BEGIN_STRING, end = END_STRING + LINE_DELIMETER, signatureParam = "Hash:" + messageDigestAlgo + " Provider:" + provider; final StringBuffer strBuf = new StringBuffer(); <START> strBuf.append(begin); <END> strBuf.append(LINE_DELIMETER); strBuf.append(signatureParam); strBuf.append(LINE_DELIMETER); strBuf.append(LINE_DELIMETER); strBuf.append(signStr); strBuf.append(LINE_DELIMETER); strBuf.append(LINE_DELIMETER); int i = 0; for (final String s : certStr.split("")) { strBuf.append(s); i++; if ((i % 48) == 0) strBuf.append(LINE_DELIMETER); } if ((i % 48) != 0) strBuf.append(LINE_DELIMETER); strBuf.append(LINE_DELIMETER); strBuf.append(end); return strBuf.toString(); }</code><technical_language>this is a constant, declare a variable for it</technical_language>

Target:
public static String getSignatureInFormat(final ScriptType scriptType, final String signStr, final String certStr, String messageDigestAlgo, String provider) throws ScriptSignatureException { if ((scriptType == null) || (signStr == null) || signStr.isEmpty() || (certStr == null) || certStr.isEmpty()) throw new ScriptSignatureException("One or more parameters are null or empty"); if ((messageDigestAlgo == null) || messageDigestAlgo.isEmpty() || "default".equalsIgnoreCase(messageDigestAlgo)) messageDigestAlgo = DEFAULT_MESSAGE_DIGEST_ALGO; if ((provider == null) || provider.isEmpty()) provider = DEFAULT_SIGNATURE_PROVIDER; final String LINE_DELIMETER = AbstractCodeFactory.LINE_DELIMITER; final String begin = AbstractCodeFactory.LINE_DELIMITER + BEGIN_STRING, end = END_STRING + AbstractCodeFactory.LINE_DELIMITER, signatureParam = "Hash:" + messageDigestAlgo + " Provider:" + provider; final StringBuffer strBuf = new StringBuffer(); strBuf.append(begin); strBuf.append(AbstractCodeFactory.LINE_DELIMITER); strBuf.append(signatureParam); strBuf.append(AbstractCodeFactory.LINE_DELIMITER + AbstractCodeFactory.LINE_DELIMITER); strBuf.append(signStr); strBuf.append(AbstractCodeFactory.LINE_DELIMITER + AbstractCodeFactory.LINE_DELIMITER); int i = 0; while (i < (certStr.length() - MAX_LENGTH)) { strBuf.append(certStr.substring(i, i + MAX_LENGTH)); strBuf.append(AbstractCodeFactory.LINE_DELIMITER); i += MAX_LENGTH; } strBuf.append(certStr.substring(i)); if (i != MAX_LENGTH) strBuf.append(AbstractCodeFactory.LINE_DELIMITER); strBuf.append(AbstractCodeFactory.LINE_DELIMITER); strBuf.append(end); return strBuf.toString(); }
Source:
<code>public @Nonnull EnvVars getEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException { Computer c = Computer.currentComputer(); Node n = c==null ? null : c.getNode(); EnvVars env = getParent().getEnvironment(n,listener); <START> for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) <END> ec.buildEnvironmentFor(this,env,listener); if (!(this instanceof AbstractBuild)) { for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) { a.buildEnvironment(this, env); } } env.putAll(getCharacteristicEnvVars()); return env; }</code><technical_language>!(this instanceof AbstractBuild) is required anymore, AbstractBuild consult super anymore</technical_language>

Target:
public @Nonnull EnvVars getEnvironment(@Nonnull TaskListener listener) throws IOException, InterruptedException { Computer c = Computer.currentComputer(); Node n = c==null ? null : c.getNode(); EnvVars env = getParent().getEnvironment(n,listener); for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) ec.buildEnvironmentFor(this,env,listener); for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) { a.buildEnvironment(this, env); } env.putAll(getCharacteristicEnvVars()); return env; }
Source:
<code>public void onDroneEvent(DroneInterfaces.DroneEventsType event, Drone drone) { <START> if(event.equals(DroneInterfaces.DroneEventsType.STATE)){ <END> if(drone.getState().isCollisionImminent()){ mPool.play(beepBeep,1f,1f,1,1,1f); }else{ mPool.stop(beepBeep); } } }</code><technical_language>@TShapinsky DroneEventsType is enum, event == DroneEventsType.STATE instead of equals() method</technical_language>

Target:
public void onDroneEvent(DroneInterfaces.DroneEventsType event, Drone drone) { if(event == DroneInterfaces.DroneEventsType.STATE){ if(drone.getState().isCollisionImminent()){ mPool.play(beepBeep,1f,1f,1,1,1f); }else{ mPool.stop(beepBeep); } } }
Source:
<code>public Double getMinimumWidth() { double minimumWidth = super.getMinimumWidth(); final GridData model = gridWidget.getModel(); final int columnIndex = getLogicalColumnIndex(model); if (columnIndex != -1) { for (GridRow row : model.getRows()) { final GridCell<?> cell = row.getCells().get(columnIndex); if (cell != null) { final GridCellValue<?> value = cell.getValue(); if (value instanceof ExpressionCellValue) { final ExpressionCellValue ecv = (ExpressionCellValue) value; final Optional<BaseExpressionGrid> editor = ecv.getValue(); <START> final double padding = editor.map(BaseExpressionGrid::getPadding).orElse(0.0); <END> minimumWidth = Math.max(minimumWidth, ecv.getMinimumWidth().orElse(0.0) + padding * 2); } } } } return minimumWidth; }</code><technical_language>BaseExpressionGrid::getPadding I this line just: java final double padding = editor.map(BaseExpressionGrid::getPadding).get(); I if apply proposed change, eliminate risk appears multiple padding in context table editor in future, WDYT</technical_language>

Target:
public Double getMinimumWidth() { double minimumWidth = super.getMinimumWidth(); final GridData model = gridWidget.getModel(); final int columnIndex = getLogicalColumnIndex(model); if (columnIndex != -1) { for (GridRow row : model.getRows()) { final GridCell<?> cell = row.getCells().get(columnIndex); if (cell != null) { final GridCellValue<?> value = cell.getValue(); if (value instanceof ExpressionCellValue) { final ExpressionCellValue ecv = (ExpressionCellValue) value; final Optional<BaseExpressionGrid> editor = ecv.getValue(); final double padding = editor.map(BaseExpressionGrid::getPadding).get(); minimumWidth = Math.max(minimumWidth, ecv.getMinimumWidth().orElse(0.0) + padding * 2); } } } } return minimumWidth; }
Source:
<code>public void verifyTableRemoved() { <START> checkIfElementOnPage(table); <END> PageObjectLogging.log("verifyTableRemoved", "table was removedcd", true); }</code><technical_language>put assertion - checkIfElementOnPage is returning true false</technical_language>

Target:
public void verifyTableRemoved() { Assertion.assertTrue(!checkIfElementOnPage(table)); PageObjectLogging.log("verifyTableRemoved", "table was removed", true); }
Source:
<code>public void testCountNumUnfiltered() { final FeatureDataSource<VariantContext> featureDataSource = new FeatureDataSource<>(new File(smallM2VcfMore)); <START> final List<VariantContext> variantContexts = new ArrayList<>(); <END> for (final VariantContext vc : featureDataSource) { variantContexts.add(vc); } Assert.assertEquals(OrientationBiasUtils.calculateUnfilteredNonRefGenotypeCount(variantContexts, "TUMOR"), 9); Assert.assertEquals(OrientationBiasUtils.calculateUnfilteredNonRefGenotypeCount(variantContexts, "NORMAL"), 0); }</code><technical_language>do this variantContexts = StreamSupport.stream(featureDataSource.spliterator(), false).collect(Collectors.toList()), is in opinion ugly ugly initializing filling lines. I a branch in gatk public turn this variantContexts = Utils.stream(featureDataSource).collect(Collectors.toList()), is a no-brainer</technical_language>

Target:
public void testCountNumUnfiltered() { final FeatureDataSource<VariantContext> featureDataSource = new FeatureDataSource<>(new File(smallM2VcfMore)); final List<VariantContext> variantContexts = getVariantContexts(featureDataSource); Assert.assertEquals(OrientationBiasUtils.calculateUnfilteredNonRefGenotypeCount(variantContexts, "TUMOR"), 9); Assert.assertEquals(OrientationBiasUtils.calculateUnfilteredNonRefGenotypeCount(variantContexts, "NORMAL"), 0); }
Source:
<code>public List<Writable> map(List<Writable> writables){ PythonVariables pyInputs = getPyInputsFromWritables(writables); try{ PythonVariables pyOutputs = PythonExecutioner.getInstance().exec(this, pyInputs); return getWritablesFromPyOutputs(pyOutputs); } catch (Exception e){ <START> throw new RuntimeException(e); <END> } }</code><technical_language>@AlexDBlack is this normal for transforms? changed in data vec transforms of</technical_language>

Target:
public List<Writable> map(List<Writable> writables){ PythonVariables pyInputs = getPyInputsFromWritables(writables); try{ PythonExecutioner.exec(code, pyInputs, pyOutputs); return getWritablesFromPyOutputs(pyOutputs); } catch (Exception e){ throw new RuntimeException(e); } }
Source:
<code>public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException { TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc)); boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(serializeNulls); try { ((TypeAdapter<Object>) adapter).write(writer, src); } catch (IOException e) { throw new JsonIOException(e); } catch (AssertionError e) { <START> throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage()); <END> } finally { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } }</code><technical_language>changing these</technical_language>

Target:
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException { TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc)); boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(serializeNulls); try { ((TypeAdapter<Object>) adapter).write(writer, src); } catch (IOException e) { throw new JsonIOException(e); } catch (AssertionError e) { AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage()); error.initCause(e); throw error; } finally { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } }
Source:
<code><START> public List<RichMember> getRichMembersWithAttributesByNames(PerunSession sess, Group group, Resource resource, List<String> attrsNames) throws InternalErrorException, AttributeNotExistsException, MemberResourceMismatchException { <END> List<Member> members = new ArrayList<Member>(); members.addAll(perunBl.getGroupsManagerBl().getGroupMembers(sess, group)); List<RichMember> richMembers = this.convertMembersToRichMembers(sess, members); List<AttributeDefinition> attrsDef = new ArrayList<AttributeDefinition>(); for(String atrrName: attrsNames) { AttributeDefinition attrDef = perunBl.getAttributesManagerBl().getAttributeDefinition(sess, atrrName); attrsDef.add(attrDef); } List<RichMember> richMembersWithAttributes = this.convertMembersToRichMembersWithAttributes(sess, group, resource, richMembers, attrsDef); return richMembersWithAttributes; }</code><technical_language>I guess checking, group resource VO, more interesting. true, is chance, member VO resource. catch MemberResourceMismatchException thrown conversion method wrap ConsistencyErrorException. add explicit check group resource throw necessary exception API layer</technical_language>

Target:
public List<RichMember> getRichMembersWithAttributesByNames(PerunSession sess, Group group, Resource resource, List<String> attrsNames) throws InternalErrorException, AttributeNotExistsException, GroupResourceMismatchException { getPerunBl().getAttributesManagerBl().checkGroupIsFromTheSameVoLikeResource(sess, group, resource); List<Member> members = new ArrayList<Member>(); members.addAll(perunBl.getGroupsManagerBl().getGroupMembers(sess, group)); List<RichMember> richMembers = this.convertMembersToRichMembers(sess, members); List<AttributeDefinition> attrsDef = new ArrayList<AttributeDefinition>(); for(String atrrName: attrsNames) { AttributeDefinition attrDef = perunBl.getAttributesManagerBl().getAttributeDefinition(sess, atrrName); attrsDef.add(attrDef); } List<RichMember> richMembersWithAttributes = null; try { richMembersWithAttributes = this.convertMembersToRichMembersWithAttributes(sess, group, resource, richMembers, attrsDef); } catch (MemberResourceMismatchException ex) { throw new ConsistencyErrorException(ex); } return richMembersWithAttributes; }
Source:
<code>public FoursquareAttributesDefinition() { String[] names = new String[] { FIRST_NAME,LAST_NAME,GENDER, HOME_CITY, BIO, EMAIL, PHOTO }; for (final String name : names) { addAttribute(name, Converters.stringConverter); } addAttribute(GENDER, Converters.genderConverter); addAttribute(FIRENDS,FoursquareConverters.friendsConverter); <START> } <END></code><technical_language>surprised: I attribute definition for CONTACT BADGES..</technical_language>

Target:
public FoursquareAttributesDefinition() { String[] names = new String[]{ FIRST_NAME, LAST_NAME, GENDER, HOME_CITY, BIO, EMAIL, PHOTO }; for (final String name : names) { addAttribute(name, Converters.stringConverter); } addAttribute(GENDER, Converters.genderConverter); addAttribute(FIRENDS, FoursquareConverters.friendsConverter); addAttribute(CONTACT, FoursquareConverters.contactConverter); addAttribute(PHOTO, FoursquareConverters.photoConverter); }
Source:
<code>private void init() { if (jp == null) { try { jp = objectMapper.getFactory().createParser(future.get()); final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_OBJECT) { QueryInterruptedException e = jp.getCodec().readValue(jp, QueryInterruptedException.class); throw e; } else if (nextToken != JsonToken.START_ARRAY) { throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url); } else { jp.nextToken(); objectCodec = jp.getCodec(); } } catch (IOException | InterruptedException | ExecutionException e) { <START> log.error(e, "Failure getting results from[%s]. Likely a timeout occurred.", url); <END> } catch (CancellationException e) { throw new QueryInterruptedException("Query cancelled"); } } }</code><technical_language>need throw some kind of exception here,</technical_language>

Target:
private void init() { if (jp == null) { try { jp = objectMapper.getFactory().createParser(future.get()); final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_OBJECT) { QueryInterruptedException e = jp.getCodec().readValue(jp, QueryInterruptedException.class); throw e; } else if (nextToken != JsonToken.START_ARRAY) { throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url); } else { jp.nextToken(); objectCodec = jp.getCodec(); } } catch (IOException | InterruptedException | ExecutionException e) { throw new RE(e, "Failure getting results from[%s] because of [%s]", url, e.getMessage()); } catch (CancellationException e) { throw new QueryInterruptedException("Query cancelled"); } } }
Source:
<code>public void setClockConfiguration(final DlmsConnectionHolder conn, final DlmsDevice device, final SetClockConfigurationRequestDto clockConfiguration) throws ProtocolAdapterException { try { this.clockConfigurationCommandExecutor.execute(conn, device, clockConfiguration); } catch (final ProtocolAdapterException e) { <START> LOGGER.error("Unexpected exception during replaceKeys.", e); <END> throw e; } }</code><technical_language>Setting clock configuration is replacing keys</technical_language>

Target:
public void setClockConfiguration(final DlmsConnectionHolder conn, final DlmsDevice device, final SetClockConfigurationRequestDto clockConfiguration) throws ProtocolAdapterException { try { this.setClockConfigurationCommandExecutor.execute(conn, device, clockConfiguration); } catch (final ProtocolAdapterException e) { LOGGER.error("Unexpected exception while setting clock configuration.", e); throw e; } }
Source:
<code>private int compareMetrics ( InternalRenderMetrics o1, InternalRenderMetrics o2 ){ int first = -1; int last = 1; int perferredMapRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getLayer() .getBlackboard()); if (perferredMapRenderer == 0) { perferredMapRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getLayer() .getStyleBlackboard()); } int perferredMapRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getLayer() .getBlackboard()); if (perferredMapRenderer2 == 0) { perferredMapRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getLayer() .getStyleBlackboard()); } if (perferredMapRenderer > perferredMapRenderer2) { return first; } if (perferredMapRenderer < perferredMapRenderer2) { return last; } perferredMapRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getMap() .getBlackboard()); perferredMapRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getMap() .getBlackboard()); if (perferredMapRenderer > perferredMapRenderer2) { return first; } <START> if (perferredMapRenderer < perferredMapRenderer2) { <END> return last; } double r1 = rate(o1); double r2 = rate(o2); if (r1 > r2) return last; if (r1 < r2) return first; return 0; }</code><technical_language>This is check in line 117. I guess a comparision (StyleBlackboard vs. Blackboard) code readable if name of variables a semantic. However, duplicated code/checks I understand</technical_language>

Target:
private int compareMetrics ( InternalRenderMetrics o1, InternalRenderMetrics o2 ){ int first = -1; int last = 1; int preferredLayerRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getLayer() .getBlackboard()); if (preferredLayerRenderer == 0) { preferredLayerRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getLayer() .getStyleBlackboard()); } int preferredLayerRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getLayer() .getBlackboard()); if (preferredLayerRenderer2 == 0) { preferredLayerRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getLayer() .getStyleBlackboard()); } if (preferredLayerRenderer > preferredLayerRenderer2) { return first; } if (preferredLayerRenderer < preferredLayerRenderer2) { return last; } int preferredMapRenderer = rateUsingBlackboardSettings(o1, o1.getRenderContext().getMap() .getBlackboard()); int preferredMapRenderer2 = rateUsingBlackboardSettings(o2, o2.getRenderContext().getMap() .getBlackboard()); if (preferredMapRenderer > preferredMapRenderer2) { return first; } if (preferredMapRenderer < preferredMapRenderer2) { return last; } double r1 = rate(o1); double r2 = rate(o2); if (r1 > r2) return last; if (r1 < r2) return first; return 0; }
Source:
<code>void createSubgroupsFromCommaSeparatedLastNames() { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, "Turing, Alan and Hopper, Grace"); var subgroups = new AutomaticPersonsGroup("", GroupHierarchyType.INDEPENDENT, StandardField.AUTHOR).createSubgroups(bibEntry); <START> assertEquals(2, subgroups.size()); <END> for (GroupTreeNode group : subgroups) { String groupName = group.getGroup().getName(); assertTrue(groupName.equals("Turing") || groupName.equals("Hopper")); } }</code><technical_language>construct a list of expected elements hand compare that. For example, if code return 3 elements, get a message "expected 2 3" - helpful. if do expected = Arrays.asList(new Keywordgroup(...), ...); assertEquals(expected, subgroups) get a nice message, showing additional group is there</technical_language>

Target:
void createSubgroupsFromCommaSeparatedLastNames() { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, "Turing, Alan and Hopper, Grace"); var subgroups = new AutomaticPersonsGroup("", GroupHierarchyType.INDEPENDENT, StandardField.AUTHOR).createSubgroups(bibEntry); var expectedSubgroups = createPersonSubGroupFrom("Turing", "Hopper"); assertEquals(expectedSubgroups, subgroups); }
Source:
<code>public void handleMessage (Message message) { try { byte[] body = base64.decode(message.getBody()); ByteArrayInputStream bais = new ByteArrayInputStream(body); Origin origin = Origin.read(bais); if (buffer != null && origin.samples.length != this.nIterations) { LOG.error("Origin {}, has iterations, expected {}", <START> origin.x, origin.y, origin.samples.length, this.nIterations); <END> error = true; } ByteArrayOutputStream pixelByteOutputStream = new ByteArrayOutputStream(origin.samples.length * 4); LittleEndianDataOutputStream pixelDataOutputStream = new LittleEndianDataOutputStream(pixelByteOutputStream); for (int i = 0, prev = 0; i < origin.samples.length; i++) { int current = origin.samples[i]; pixelDataOutputStream.writeInt(current - prev); prev = current; } pixelDataOutputStream.close(); synchronized (this) { if (buffer == null) this.initialize(origin.samples.length); int index1d = origin.y * request.width + origin.x; long offset = DATA_OFFSET + index1d * 4 * nIterations; buffer.seek(offset); buffer.write(pixelByteOutputStream.toByteArray()); if (!originsReceived.get(index1d)) { originsReceived.set(index1d); nComplete += 1; } if (nComplete == nTotal && !error) finish(); } } catch (Exception e) { error = true; LOG.error("Error assembling results for query {}", request.jobId, e); return; } }</code><technical_language>Again, I benefit renaming some fields revising terminology. Samples "values", log message reference "values cell" "iterations"</technical_language>

Target:
public void handleMessage (Message message) { try { byte[] body = base64.decode(message.getBody()); ByteArrayInputStream bais = new ByteArrayInputStream(body); Origin origin = Origin.read(bais); if (buffer != null && origin.samples.length != this.nIterations) { LOG.error("Origin {}, has samples, expected {}", origin.x, origin.y, origin.samples.length, this.nIterations); error = true; } ByteArrayOutputStream pixelByteOutputStream = new ByteArrayOutputStream(origin.samples.length * 4); LittleEndianDataOutputStream pixelDataOutputStream = new LittleEndianDataOutputStream(pixelByteOutputStream); for (int i = 0, prev = 0; i < origin.samples.length; i++) { int current = origin.samples[i]; pixelDataOutputStream.writeInt(current - prev); prev = current; } pixelDataOutputStream.close(); synchronized (this) { if (buffer == null) this.initialize(origin.samples.length); int index1d = origin.y * request.width + origin.x; long offset = DATA_OFFSET + index1d * 4 * nIterations; buffer.seek(offset); buffer.write(pixelByteOutputStream.toByteArray()); if (!originsReceived.get(index1d)) { originsReceived.set(index1d); nComplete += 1; } if (nComplete == nTotal && !error) finish(); } } catch (Exception e) { error = true; LOG.error("Error assembling results for query {}", request.jobId, e); return; } }
Source:
<code>void start() throws IOException { RefTree tree = queuedTree; <START> queuedTree = null; <END> for (Proposal p : todo) { p.notifyState(RUNNING); } begin(tree); }</code><technical_language>This is assigned a local variable, set null, local variable is passed other methods. pass start() method get rid of member variable setTree() method</technical_language>

Target:
void start() throws IOException { for (Proposal p : todo) { p.notifyState(RUNNING); } try { ObjectId id; try (Repository git = leader.openRepository()) { id = insertProposals(git); } acceptAsync(id); } catch (NoOp e) { for (Proposal p : todo) { p.success(); } leader.lock.lock(); try { leader.nextRound(); } finally { leader.lock.unlock(); } } catch (IOException e) { abort(JGitText.get().transactionAborted); throw e; } }
Source:
<code>private ProtocolVersion getVersionFromString(String version) { <START> if (version.equals("1.0")) { <END> return ProtocolVersion.DTLSv10; } else if (version.equals("1.2")) { return ProtocolVersion.DTLSv12; } else { throw new IllegalArgumentException("Invalid DTLS version"); } }</code><technical_language>"1.0".equals(version) avoid NPE</technical_language>

Target:
private ProtocolVersion getVersionFromString(String version) { if ("1.0".equals(version)) { return ProtocolVersion.DTLSv10; } else if ("1.2".equals(version)) { return ProtocolVersion.DTLSv12; } else { throw new IllegalArgumentException("Invalid DTLS version"); } }
Source:
<code><START> public HashMap<UUID, Object> readMapFromJson() { <END> try { Type mapType = new TypeToken<HashMap<UUID, Object>>() { }.getType(); return new Gson().fromJson(new FileReader(deviceFile), mapType); } catch (FileNotFoundException e) { if (deviceFile.exists()) { Log.e(TAG, "Device Variable File corrupted!"); deviceFile.delete(); } return null; } }</code><technical_language>SonarLint: purpose of Java Collections API is provide a defined hierarchy of interfaces in order hide implementation details. Implementing classes instantiate new collections, result of instantiation ideally stored in a variable type is a Java Collection interface. This rule raises issue implementation class: - is returned a public method. - is accepted argument a public method. - is exposed a public member. Noncompliant Code Example public class Employees { private HashSet<Employee> employees = new HashSet<Employee>(); // Noncompliant - "employees" type "Set" "HashSet" public HashSet<Employee> getEmployees() { // Noncompliant return employees; } } Compliant Solution public class Employees { private Set<Employee> employees = new HashSet<Employee>(); // Compliant public Set<Employee> getEmployees() { // Compliant return employees; } }</technical_language>

Target:
public Map<UUID, Object> readMapFromJson() { try { Type mapType = new TypeToken<HashMap<UUID, Object>>() { }.getType(); return new Gson().fromJson(new FileReader(deviceFile), mapType); } catch (FileNotFoundException e) { if (deviceFile.exists()) { Log.e(TAG, "Device Variable File corrupted!"); deviceFile.delete(); } return null; } }
Source:
<code>CalciteAdHocCompilerCache(int maxLiteralEntries, int maxCoreEntries) { <START> MAX_LITERAL_ENTRIES = maxLiteralEntries; <END> MAX_CORE_ENTRIES = maxCoreEntries; m_literalCache = new AdHocStatementCache(MAX_LITERAL_ENTRIES, MAX_LITERAL_MEM); m_coreCache = new LinkedHashMap<String, CorePlan>(MAX_CORE_ENTRIES * 2, .75f, true) { private static final long serialVersionUID = 1L; @Override public boolean removeEldestEntry(Map.Entry<String, CorePlan> eldest) { if (size() > MAX_CORE_ENTRIES) { ++m_planEvictions; return true; } return false; } }; }</code><technical_language>initialize static members in constructor? need a static method set those. Do need initialized some method? fixed work</technical_language>

Target:
CalciteAdHocCompilerCache(int maxLiteralEntries, int maxCoreEntries) { m_literalCache = new AdHocStatementCache(maxLiteralEntries, MAX_LITERAL_MEM) { private static final long serialVersionUID = 1L; @Override public boolean removeEldestEntry(final Map.Entry<String, AdHocPlannedStatement> eldest) { if ((size() > maxEntries) || (this.currentMemory > this.maxMemory)) { ++m_literalEvictions; this.currentMemory -= eldest.getValue().getSerializedSize(); return true; } return false; } }; m_coreCache = new LinkedHashMap<String, CorePlan>(maxCoreEntries, .75f, true) { private static final long serialVersionUID = 1L; @Override public boolean removeEldestEntry(Map.Entry<String, CorePlan> eldest) { if (size() > maxCoreEntries) { ++m_planEvictions; return true; } return false; } }; }
Source:
<code>public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { logger.error("---------------------------" + e.getLocalizedMessage()); <START> logger.error("--do nothing in case of some failed tests to avoid next test to fail as well-------------------------" + unit.getIdentifier()); <END> } } units.clear(); } close(); }</code><technical_language>Do need this logging? decrease logging level debug pollute logs tests run</technical_language>

Target:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { } } units.clear(); } close(); }
Source:
<code><START> public static Boolean isPython(String[] programArguments){ <END> return CollectionUtils.containsAny(Arrays.asList(programArguments), Arrays.asList("-py", "-pym", "--python", "--pyModule")); }</code><technical_language>suggestion public static boolean isPython(String[] programArguments){</technical_language>

Target:
public static boolean isPython(String[] programArguments){ return CollectionUtils.containsAny(Arrays.asList(programArguments), Arrays.asList("-py", "-pym", "--python", "--pyModule")); }
Source:
<code>private ProviderNetwork getExternalNetwork() { if (externalNetwork == null) { <START> Network network = getNetworkDAO().get(getParameters().getNetworkId()); <END> externalNetwork = network.getProvidedBy(); } return externalNetwork; }</code><technical_language>guarantees getParameters().getNetworkId()) represents a real network</technical_language>

Target:
private ProviderNetwork getExternalNetwork() { if (externalNetwork == null) { Network network = getNetworkDAO().get(getParameters().getNetworkId()); if (network != null) { externalNetwork = network.getProvidedBy(); } } return externalNetwork; }
Source:
<code>private DependencyAttribute newDependsOn(Change c, PatchSet ps) { DependencyAttribute d = newDependencyAttribute(c, ps); <START> d.isCurrentPatchSet = new Boolean(c.currPatchSetId().equals(ps.getId())); <END> return d; }</code><technical_language>Nit: This is autoboxed dont need call constructor explicitly</technical_language>

Target:
private DependencyAttribute newDependsOn(Change c, PatchSet ps) { DependencyAttribute d = newDependencyAttribute(c, ps); d.isCurrentPatchSet = c.currPatchSetId().equals(ps.getId()); return d; }
Source:
<code>private void setOurs() throws IOException { if (baseCommit != null) { ours = NoteMap.read(db.newObjectReader(), baseCommit); } else { ours = NoteMap.newEmptyMap(); } StringBuilder message = <START> new StringBuilder("Submitted the following changes:"); <END> for (CodeReviewCommit c : commits) { if (ours.contains(c)) { throw new IllegalStateException( "Review summary note already exists for commit: " + c + ". Merging of notes not yet supported"); } ObjectId id = inserter.insert(Constants.OBJ_BLOB, createNoteContent(c)); inserter.flush(); RevBlob blob = revWalk.lookupBlob(id); ours.set(c, blob); message.append(" "); message.append(c.change.getId()); } message.append("\n"); if (baseCommit != null) { oursCommit = createCommit(ours, author, message.toString(), baseCommit); } else { oursCommit = createCommit(ours, author, message.toString()); } }</code><technical_language>This a big oneline summary. instead do: StringBuilder message = new StringBuilder(); message.append("Update notes for submitted changes\n\n"); for (CodeReviewCommit c : commits) { ... message.append("* ").append(c.getShortMessage()).append("\n"); }</technical_language>

Target:
private void setOurs() throws IOException, CodeReviewNoteCreationException { if (baseCommit != null) { ours = NoteMap.read(db.newObjectReader(), baseCommit); } else { ours = NoteMap.newEmptyMap(); } StringBuilder message = new StringBuilder("Update notes for submitted changes\n\n"); for (CodeReviewCommit c : commits) { ObjectId noteContent = createNoteContent(c); if (ours.contains(c)) { DefaultNoteMerger noteMerger = new DefaultNoteMerger(); Note newNote = new Note(c, noteContent); noteContent = noteMerger.merge(null, newNote, base.getNote(c), reader, inserter) .getData(); } ours.set(c, noteContent); message.append("* ").append(c.getShortMessage()).append("\n"); } if (baseCommit != null) { oursCommit = createCommit(ours, author, message.toString(), baseCommit); } else { oursCommit = createCommit(ours, author, message.toString()); } }
Source:
<code>void checkViewModelFile(IResource iResource, IProgressMonitor monitor) { if (isViewModelResource(iResource)) { final IFile file = IFile.class.cast(iResource); <START> monitor.subTask(String.format("Checking %s", file.getName())); END> projectMarkerHelper.deleteMarkers(file); try { final Optional<BasicDiagnostic> diagnostics = validateView(file); if (diagnostics.isPresent()) { final Diagnostic diag = diagnostics.get(); if (diag.getSeverity() >= IMarker.SEVERITY_WARNING) { final MarkerHelper markerHelper = new ViewModelMarkerHelper(file); markerHelper.createMarkers(diag); } } } catch (final CoreException ex) { Activator.log("Errors while creating markers on file " + file, ex); } } }</code><technical_language>this string externalized Eclipse NLS API</technical_language>

Target:
void checkViewModelFile(IResource iResource, IProgressMonitor monitor) { if (isViewModelResource(iResource)) { final IFile file = IFile.class.cast(iResource); monitor.subTask(NLS.bind(Messages.ViewModelBuilder_Subtask_Label, file.getName())); projectMarkerHelper.deleteMarkers(file); try { final Optional<BasicDiagnostic> diagnostics = validateView(file); if (diagnostics.isPresent()) { final Diagnostic diag = diagnostics.get(); if (diag.getSeverity() >= IMarker.SEVERITY_WARNING) { final MarkerHelper markerHelper = new ViewModelMarkerHelper(file); markerHelper.createMarkers(diag); } } } catch (final CoreException ex) { Activator.log("Errors while creating markers on file " + file, ex); } } }
Source:
<code>private void determineCipherSuitesFromConfig() { List<CipherSuite> ciphers = new ArrayList<>(); boolean certificates = isConfiguredWithKeyPair() || config.trustCertificateTypes != null; <START> boolean recommendedOnly = Boolean.FALSE.equals(recommendedCipherSuitesOnly); <END> if (certificates) { ciphers.addAll(CipherSuite.getEcdsaCipherSuites(recommendedOnly)); } if (config.pskStore != null) { ciphers.addAll(CipherSuite.getPskCipherSuites(recommendedOnly, true)); } config.supportedCipherSuites = ciphers; }</code><technical_language>I prefer define a default for recommendedCipherSuitesOnly call determineCipherSuitesFromConfig instead of this test here</technical_language>

Target:
private void determineCipherSuitesFromConfig() { List<CipherSuite> ciphers = new ArrayList<>(); boolean certificates = isConfiguredWithKeyPair() || config.trustCertificateTypes != null; if (certificates) { ciphers.addAll(CipherSuite.getEcdsaCipherSuites(recommendedCipherSuitesOnly)); } if (config.pskStore != null) { ciphers.addAll(CipherSuite.getPskCipherSuites(recommendedCipherSuitesOnly, true)); } config.supportedCipherSuites = ciphers; }
Source:
<code>private static boolean isLimitAll(String limitClause) { <START> return Pattern.compile("all", CASE_INSENSITIVE).matcher(limitClause).matches(); <END> }</code><technical_language>nit: move Pattern.compile("all", CASE_INSENSITIVE) a static variable avoid re-compiling call</technical_language>

Target:
private static boolean isLimitAll(String limitClause) { return limitClause.toLowerCase(ENGLISH).equals("all"); }
Source:
<code><START> public void eventDispatched(IStartedDMEvent event) { <END> final IMemoryDMContext memContext = DMContexts.getAncestorOfType(event.getDMContext(), IMemoryDMContext.class); final IMIExecutionDMContext execContext = DMContexts.getAncestorOfType(event.getDMContext(), IMIExecutionDMContext.class); if (memContext != null && execContext != null) { getExecutor().execute(new DsfRunnable() { @Override public void run() { readAddressSize(memContext, execContext); readEndianness(memContext, execContext); } }); } }</code><technical_language>This trigger for thread exists also. dealing a process using: if (event.getDMContext() instanceof IContainerDMContext)</technical_language>

Target:
public void eventDispatched(IStartedDMEvent event) { if (event.getDMContext() instanceof IContainerDMContext) { IMemoryDMContext memContext = DMContexts.getAncestorOfType(event.getDMContext(), IMemoryDMContext.class); if (memContext != null) { readAddressSize(memContext); readEndianness(memContext); } } }
Source:
<code>protected IPath getCompilationPath(ISourceContainer[] containers, String sourceName) { for (ISourceContainer container : containers) { if (container instanceof MappingSourceContainer <START> && ((MappingSourceContainer) container).isMappingWithBackendEnabled()) { <END> } else if (container instanceof IMappingSourceContainer) { IPath path = ((IMappingSourceContainer) container).getCompilationPath(sourceName); if (path != null) { return path; } } ISourceContainer[] childContainers = null; try { childContainers = container.getSourceContainers(); } catch (CoreException e) { } if (childContainers != null) { IPath path = getCompilationPath(childContainers, sourceName); if (path != null) { return path; } } } return null; }</code><technical_language>need check this mapping corresponds passed sourceName? This put return below? this approach fail in obscure case. I create correct mapping backend, follow a mapping backend, return a new path wrong one. mapping precedence break things. thinking find a valid mapping, it</technical_language>

Target:
protected IPath getCompilationPath(ISourceContainer[] containers, String sourceName) { for (ISourceContainer container : containers) { if (container instanceof IMappingSourceContainer) { if (container instanceof MappingSourceContainer && ((MappingSourceContainer) container).isMappingWithBackendEnabled()) { return null; } return ((IMappingSourceContainer) container).getCompilationPath(sourceName); } ISourceContainer[] childContainers = null; try { childContainers = container.getSourceContainers(); } catch (CoreException e) { } if (childContainers != null) { IPath path = getCompilationPath(childContainers, sourceName); if (path != null) { return path; } } } return null; }
Source:
<code>public String scheduleAFixedDelayJob(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, long taskDelay, TimeUnit timeUnit) { executor.scheduleWithFixedDelay(getRunnable(instance, methodName, inputTypes, inputParams), initialDelay, taskDelay, TimeUnit.SECONDS); <START> return "JOB::scheduleAFixedDelayJob::" + methodName; <END> }</code><technical_language>please generateUniqueNameForInstance(instance, methodName);</technical_language>

Target:
public String scheduleAFixedDelayJob(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, long taskDelay, TimeUnit timeUnit) { executor.scheduleWithFixedDelay(getRunnable(instance, methodName, inputTypes, inputParams), initialDelay, taskDelay, TimeUnit.SECONDS); return generateUniqueNameForInstance(instance, methodName); }
Source:
<code>public boolean login() throws LoginException { boolean loginOk = false; final CredentialsCallback cb = new CredentialsCallback(); try { callbackHandler.handle(new Callback[]{cb}); credentials = cb.getCredentials(); } catch (Exception e) { throw new LoginException(e.getClass().getName() + ":" + e.getMessage()); } if(credentials == null) { logger.log(Level.WARNING, "Credentials could not be retrieved!"); return false; } logger.log(Level.INFO, "Authenticating " + SecurityUtil.getCredentialsFullName(credentials)); if (credentials instanceof UsernamePasswordCredentials){ loginOk = doLoginCheck((UsernamePasswordCredentials) credentials); } <START> return loginOk; <END> }</code><technical_language>authentication fails, LoginException thrown. FailedLoginException child class is candidate. Returning false means login module ignored. for instance login module stack contains modules, accepting parameters. Return false in case actual parameters sufficient for current login module</technical_language>

Target:
public boolean login() throws LoginException { boolean loginOk = true; final CredentialsCallback cb = new CredentialsCallback(); try { callbackHandler.handle(new Callback[]{cb}); credentials = cb.getCredentials(); } catch (Exception e) { logger.log(Level.WARNING, e.getClass().getName() + ":" + e.getMessage()); return false; } if (credentials == null) { logger.log(Level.WARNING, "Credentials could not be retrieved!"); return false; } logger.log(Level.INFO, "Authenticating " + SecurityUtil.getCredentialsFullName(credentials)); if (credentials instanceof UsernamePasswordCredentials) { doLoginCheck((UsernamePasswordCredentials) credentials); } else { logger.log(Level.WARNING, "Credentials were not of expected class type of " + UsernamePasswordCredentials.class.getName()); return false; } return loginOk; }
Source:
<code>protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) { String value = retrieveParameterValueFromWebOrJNDIConfiguration(filterConfig, propertyName); if (CommonUtils.isNotBlank(value)) { return value; } <START> value = retrieveParameterValueFromConfigFile(filterConfig, propertyName, "/etc/cas/client.properties"); <END> if (CommonUtils.isNotBlank(value)) { return value; } logger.info("Property not found. Using default value [{}]", propertyName, defaultValue); return defaultValue; }</code><technical_language>I this filename definable this directory work Windows..</technical_language>

Target:
protected final String getPropertyFromInitParams(final FilterConfig filterConfig, final String propertyName, final String defaultValue) { String value = retrieveParameterValueFromWebOrJNDIConfiguration(filterConfig, propertyName); if (CommonUtils.isNotBlank(value)) { return value; } value = retrieveParameterValueFromConfigFile(filterConfig, propertyName, PARAM_VALUE_DEFAULT_CONFIG_FILE); if (CommonUtils.isNotBlank(value)) { return value; } logger.info("Property not found. Using default value [{}]", propertyName, defaultValue); return defaultValue; }
Source:
<code>protected void revertTask() { Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId(); Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId(); DiskImage diskImage = getDiskImageDao().get(destinationImageId); <START> if (diskImage != null && diskImage.getStorageIds().get(0) == targetStorageDomainId) { <END> getEnclosingCommand().getParameters().setExecutionIndex(0); } }</code><technical_language>equals - is guarantee Guid instance</technical_language>

Target:
protected void revertTask() { Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId(); Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId(); DiskImage diskImage = getDiskImageDao().get(destinationImageId); if (diskImage != null && targetStorageDomainId.equals(diskImage.getStorageIds().get(0))) { getEnclosingCommand().getParameters().setExecutionIndex(0); } }
Source:
<code>private String token() throws IOException { final String uri = new Href("<LINK_0>") .with("grant_type", "client_credentials") .toString(); return new JdkRequest(uri) .method("POST") .header( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" ) .header( "Authorization", <START> "Basic ".concat( <END> PsTwitter.prepareAuthKey( this.app, this.key ) ) ) .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readObject().getString("access_token"); }</code><technical_language>more natural String.format()</technical_language>

Target:
private String token() throws IOException { final String uri = new Href("<LINK_0>") .with("grant_type", "client_credentials") .toString(); return new JdkRequest(uri) .method("POST") .header( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" ) .header( "Authorization", String.format( "Basic %s", DatatypeConverter.printBase64Binary( String.format("%s:%s", this.app, this.key).getBytes() ) ) ) .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readObject().getString("access_token"); }
Source:
<code>public List<? extends Node> getChildren() { return ImmutableList.<Node>builder() <START> .addAll(properties).build(); <END> }</code><technical_language>table? - move .build() separate line</technical_language>

Target:
public List<? extends Node> getChildren() { return properties; }
Source:
<code>static ReadExecutionController forCommand(ReadCommand command) { ColumnFamilyStore baseCfs = Keyspace.openAndGetStore(command.metadata()); ColumnFamilyStore indexCfs = maybeGetIndexCfs(baseCfs, command); ReadExecutionController result; if (indexCfs == null) { result = new ReadExecutionController(command, baseCfs.readOrdering.start(), baseCfs.metadata(), null, null); } else { OpOrder.Group baseOp = null; WriteContext writeContext = null; ReadExecutionController indexController = null; try { baseOp = baseCfs.readOrdering.start(); indexController = new ReadExecutionController(command, indexCfs.readOrdering.start(), indexCfs.metadata(), null, null); writeContext = baseCfs.keyspace.getWriteHandler().createContextForRead(); result = new ReadExecutionController(command, baseOp, baseCfs.metadata(), indexController, writeContext); } catch (RuntimeException e) { assert writeContext == null; try { if (baseOp != null) baseOp.close(); } finally { if (indexController != null) indexController.close(); } throw e; } } if (baseCfs.metric.topLocalReadQueryTime.isEnabled()) <START> { <END> result.startTime = System.nanoTime(); } return result; }</code><technical_language>Single line if conditions need braces</technical_language>

Target:
static ReadExecutionController forCommand(ReadCommand command) { ColumnFamilyStore baseCfs = Keyspace.openAndGetStore(command.metadata()); ColumnFamilyStore indexCfs = maybeGetIndexCfs(baseCfs, command); ReadExecutionController result; if (indexCfs == null) { result = new ReadExecutionController(command, baseCfs.readOrdering.start(), baseCfs.metadata(), null, null); } else { OpOrder.Group baseOp = null; WriteContext writeContext = null; ReadExecutionController indexController = null; try { baseOp = baseCfs.readOrdering.start(); indexController = new ReadExecutionController(command, indexCfs.readOrdering.start(), indexCfs.metadata(), null, null); writeContext = baseCfs.keyspace.getWriteHandler().createContextForRead(); result = new ReadExecutionController(command, baseOp, baseCfs.metadata(), indexController, writeContext); } catch (RuntimeException e) { assert writeContext == null; try { if (baseOp != null) baseOp.close(); } finally { if (indexController != null) indexController.close(); } throw e; } } if (baseCfs.metric.topLocalReadQueryTime.isEnabled()) result.startTimeNanos = clock.nanoTime(); return result; }