auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String checkFileCharset(File propsFile) throws IOException { String[] charsetsToBeTested = {"US-ASCII", "UTF-8", "ISO-8859-1"}; for (String charsetName : charsetsToBeTested) { Charset charsetDet = Charset.forName(charsetName); CharsetDecoder decoder = charsetDet.newDecoder(); decoder.reset(); <START> BufferedInputStream input = new BufferedInputStream(new FileInputStream(propsFile)); <END> byte[] buffer = new byte[512]; boolean identified = true; while ((input.read(buffer) != -1) && (identified)) { try { decoder.decode(ByteBuffer.wrap(buffer)); identified = true; } catch (CharacterCodingException e) { identified = false; } } if (identified == true){ return charsetName;} } return null; }</code><technical_language>Do need close</technical_language>

Target:
public static Charset checkFileCharset(File propsFile) throws IOException { List<Charset> charsetsToBeTested = Arrays.asList(US_ASCII, UTF_8, ISO_8859_1); for (Charset charsetTest : charsetsToBeTested) { CharsetDecoder decoder = charsetTest.newDecoder(); decoder.reset(); boolean identified = true; try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(propsFile))) { byte[] buffer = new byte[512]; while ((input.read(buffer) != -1) && (identified)) { try { decoder.decode(ByteBuffer.wrap(buffer)); identified = true; } catch (CharacterCodingException e) { identified = false; } } } if (identified == true){ return charsetTest; } } return null; }
Source:
<code>public void testSysPurposePoolPriorityUseCase9PremiumSLADevelopmentUsage() throws NoSuchMethodException { consumer.setRole("RHEL Server"); consumer.setServiceLevel("Premium"); consumer.setUsage("Development"); Product prodRH00009 = new Product(); prodRH00009.setAttribute("roles", "RHEL Server"); prodRH00009.setAttribute("addons", "Smart Management"); prodRH00009.setAttribute("support_level", "Standard"); prodRH00009.setAttribute("usage", "Production"); Pool RH00009 = TestUtil.createPool(owner, prodRH00009); RH00009.setId("RH00009"); Product prodRH00008 = new Product(); <START> prodRH00008.setAttribute("roles", "RHEL Server"); <END> prodRH00008.setAttribute("addons", "Smart Management"); prodRH00008.setAttribute("support_level", "Premium"); prodRH00008.setAttribute("usage", "Production"); Pool RH00008 = TestUtil.createPool(owner, prodRH00008); RH00008.setId("RH00008"); jsRules.reinitTo("test_name_space"); JsonJsContext args = new JsonJsContext(mapper); args.put("log", log, false); args.put("consumer", consumer); args.put("compliance", compliance); args.put("pool", RH00009); Double RH00009Priority = jsRules.invokeMethod("get_pool_priority_test", args); args.put("pool", RH00008); Double RH00008Priority = jsRules.invokeMethod("get_pool_priority_test", args); assertTrue("Pool RH00008 should have a higher priority than pool RH00009.", RH00008Priority > RH00009Priority); }</code><technical_language>Yeah, a comma-delimited string works for me. In fact, I storing values comma-delimited strings in DB method more in-line happening elsewhere. Good idea</technical_language>

Target:
public void testSysPurposePoolPriorityUseCase9PremiumSLADevelopmentUsage() throws NoSuchMethodException { consumer.setRole("RHEL Server"); consumer.setServiceLevel("Premium"); consumer.setUsage("Development"); Product prodRH00009 = createSysPurposeProduct(null, "RHEL Server", "Smart Management", "Standard", "Production"); Pool RH00009 = TestUtil.createPool(owner, prodRH00009); RH00009.setId("RH00009"); Product prodRH00008 = createSysPurposeProduct(null, "RHEL Server", "Smart Management", "Premium", "Production"); Pool RH00008 = TestUtil.createPool(owner, prodRH00008); RH00008.setId("RH00008"); jsRules.reinitTo("test_name_space"); JsonJsContext args = new JsonJsContext(mapper); args.put("log", log, false); args.put("consumer", consumer); args.put("compliance", compliance); args.put("pool", RH00009); Double RH00009Priority = jsRules.invokeMethod("get_pool_priority_test", args); args.put("pool", RH00008); Double RH00008Priority = jsRules.invokeMethod("get_pool_priority_test", args); assertTrue("Pool RH00008 should have a higher priority than pool RH00009.", RH00008Priority > RH00009Priority); }
Source:
<code>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream input = null; try { input = getClass().getClassLoader().getResourceAsStream(META_RESOURCE_IN_JAR_STATIC); <START> BufferedReader reader = new BufferedReader(new InputStreamReader(input)); <END> resp.getWriter().write(reader.readLine()); resp.flushBuffer(); } finally { if (input != null) { input.close(); } } }</code><technical_language>resource leak</technical_language>

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try (InputStream input = getClass().getClassLoader().getResourceAsStream(META_RESOURCE_IN_JAR_STATIC); InputStreamReader inputReader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputReader)) { resp.getWriter().write(reader.readLine()); resp.flushBuffer(); } }
Source:
<code>public Observable<Void> unregister() { logger.debug("Unregistering service in registry: {}", currentInfo); if (!moveToState(STATES.Registered, STATES.Closed)) { STATES currentState = state.get(); if (currentState == STATES.Idle) { <START> sendErrorOnTransport(INSTANCE_ALREADY_REGISTERED_EXCEPTION); <END> return Observable.error(INSTANCE_NOT_REGISTERED_EXCEPTION); } if (currentState == STATES.Closed) { return Observable.error(CHANNEL_CLOSED_EXCEPTION); } return Observable.error(new IllegalStateException("Unrecognized channel state: " + currentState)); } Observable<Boolean> updateResult = registry.unregister(currentInfo); updateResult.subscribe(new Subscriber<Boolean>() { @Override public void onCompleted() { currentInfo = null; sendAckOnTransport(); } @Override public void onError(Throwable e) { sendErrorOnTransport(e); } @Override public void onNext(Boolean status) { } }); return updateResult.ignoreElements().cast(Void.class); }</code><technical_language>Invalid error</technical_language>

Target:
public Observable<Void> unregister() { logger.debug("Unregistering service in registry: {}", currentInfo); if (!moveToState(STATES.Registered, STATES.Closed)) { STATES currentState = state.get(); if (currentState == STATES.Idle) { sendErrorOnTransport(INSTANCE_NOT_REGISTERED_EXCEPTION); return Observable.error(INSTANCE_NOT_REGISTERED_EXCEPTION); } if (currentState == STATES.Closed) { return Observable.error(CHANNEL_CLOSED_EXCEPTION); } return Observable.error(new IllegalStateException("Unrecognized channel state: " + currentState)); } Observable<Boolean> updateResult = registry.unregister(currentInfo); updateResult.subscribe(new Subscriber<Boolean>() { @Override public void onCompleted() { currentInfo = null; sendAckOnTransport(); } @Override public void onError(Throwable e) { sendErrorOnTransport(e); } @Override public void onNext(Boolean status) { } }); return updateResult.ignoreElements().cast(Void.class); }
Source:
<code>public void fromBinary( byte[] bytes ) { int offset = 0; <START> maxVertices = (int) bytes[offset]; <END> offset += 4; simpVertMin = (int) bytes[offset]; offset += 4; tolerance = (double) bytes[offset]; offset += 4; }</code><technical_language>array of size 3 if did...suggest a bytebuffer</technical_language>

Target:
public void fromBinary( byte[] bytes ) { ByteBuffer buf = ByteBuffer.wrap(bytes); maxVertices = buf.getInt(); simpVertMin = buf.getInt(); tolerance = buf.getDouble(); }
Source:
<code>public static <T> String extractSchemaName(Class<T> clazz) { DatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class); if (databaseTable != null && databaseTable.schemaName() != null && databaseTable.schemaName().length() > 0) { return databaseTable.schemaName(); } else { <START> return ""; <END> } }</code><technical_language>This null "" right</technical_language>

Target:
public static <T> String extractSchemaName(Class<T> clazz) { DatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class); if (databaseTable != null && databaseTable.schemaName().length() > 0) { return databaseTable.schemaName(); } else { return null; } }
Source:
<code>public VersionInfo getCurrentVersion(@RequestParam(name = "token", required = true) String token) throws InvalidMonitoringTokenException, IOException { if (StringUtils.isNotEmpty(token) && StringUtils.equals(token, getConfiguredToken())) { return VersionInfo.getVersion(this.getClass()); } else { <START> throw new InvalidMonitoringTokenException("Invalid token for monitoring authorization"); <END> } }</code><technical_language>Change message of exception Monitoring authorization failed, invalid token</technical_language>

Target:
public VersionInfo getCurrentVersion(@RequestParam(name = "token", required = true) String token) throws InvalidManagementTokenException, IOException { if (StringUtils.isNotEmpty(token) && StringUtils.equals(token, getConfiguredToken())) { return VersionInfo.getVersion(this.getClass()); } else { throw new InvalidManagementTokenException("Management authorization failed, invalid token."); } }
Source:
<code>public void merge(SuiteResult sr) { <START> if (hasTimeAttr) { <END> duration += sr.getDuration(); } for (CaseResult cr : sr.getCases()) { addCase(cr); cr.replaceParent(this); } }</code><technical_language>sr.hasTimeAttr</technical_language>

Target:
public void merge(SuiteResult sr) { if (sr.hasTimeAttr() ^ hasTimeAttr()){ LOGGER.warning("Merging of suiteresults with incompatible time attribute may lead to incorrect durations in reports.( "+getFile()+", "+sr.getFile()+")"); } if (hasTimeAttr()) { duration += sr.getDuration(); } for (CaseResult cr : sr.getCases()) { addCase(cr); cr.replaceParent(this); } }
Source:
<code>public int skipBytes(int n) throws EOFException { return (int) skip(n); <START> } <END></code><technical_language>This new checkPosLength(int) method well</technical_language>

Target:
public int skipBytes(int n) throws EOFException { checkPosLength(n); return (int) skip(n); }
Source:
<code>public String toString() { return toStringHelper(this) .add("id", id) .add("partitioning", partitioning) <START> .add("partitionedSource", tableScanSchedulingOrder) <END> .add("partitionFunction", partitioningScheme) .toString(); }</code><technical_language>tableScanSchedulingOrder</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("id", id) .add("partitioning", partitioning) .add("tableScanSchedulingOrder", tableScanSchedulingOrder) .add("partitionFunction", partitioningScheme) .toString(); }
Source:
<code><START> public static void loadDataFromCounters(HashMap<Integer, Long> map, Counters jobCounters) { <END> for (Group g : jobCounters) { if (g.getName().equals("kmerLength-bins")) { for (Counter c : g) { Integer X = Integer.parseInt(c.getName()); if (map.get(X) != null) { map.put(X, map.get(X) + c.getCounter()); } else { map.put(X, c.getCounter()); } } } } }</code><technical_language>this more sense if _returned_ a map modifying in-place</technical_language>

Target:
public static HashMap<Integer, Long> loadDataFromCounters(HashMap<Integer, Long> map, Counters jobCounters) { for (Group g : jobCounters) { if (g.getName().equals("kmerLength-bins")) { for (Counter c : g) { Integer X = Integer.parseInt(c.getName()); if (map.get(X) != null) { map.put(X, map.get(X) + c.getCounter()); } else { map.put(X, c.getCounter()); } } } } return map; }
Source:
<code>public <TYPE> TYPE followLink(TYPE object) { if (!isLink(object)) { throw new RuntimeException("Can't follow link because object don't have any."); } try { <START> String href = ((Identified)object).href(); <END> if (href == null) { throw new RuntimeException("Can't follow link because the 'href' attribute does't have a value"); } URL url = new URL(getUrl()); String prefix = url.getPath(); if (!prefix.endsWith("/")) { prefix += "/"; } if (!href.startsWith(prefix)) { throw new RuntimeException("The URL '" + href + "' isn't compatible with the base URL of the connection"); } String path = href.substring(prefix.length()); Service service = systemService().service(path); Method get = service.getClass().getMethod("get"); get.setAccessible(true); Object getRequest = get.invoke(service); Method send = getRequest.getClass().getMethod("send"); send.setAccessible(true); Object getReponse = send.invoke(getRequest); Method obtainObject = getReponse.getClass().getDeclaredMethods()[0]; obtainObject.setAccessible(true); return (TYPE)obtainObject.invoke(getReponse); } catch (NoSuchMethodException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } }</code><technical_language>Same, space cast operator</technical_language>

Target:
public <TYPE> TYPE followLink(TYPE object) { if (!isLink(object)) { throw new RuntimeException("Can't follow link because object don't have any."); } try { String href = ((Identified) object).href(); if (href == null) { throw new RuntimeException("Can't follow link because the 'href' attribute does't have a value"); } URL url = new URL(getUrl()); String prefix = url.getPath(); if (!prefix.endsWith("/")) { prefix += "/"; } if (!href.startsWith(prefix)) { throw new RuntimeException("The URL '" + href + "' isn't compatible with the base URL of the connection"); } String path = href.substring(prefix.length()); Service service = systemService().service(path); Method get = service.getClass().getMethod("get"); Object getRequest = get.invoke(service); Method send = getRequest.getClass().getMethod("send"); send.setAccessible(true); Object getResponse = send.invoke(getRequest); Method obtainObject = getResponse.getClass().getDeclaredMethods()[0]; obtainObject.setAccessible(true); return (TYPE) obtainObject.invoke(getResponse); } catch (NoSuchMethodException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } }
Source:
<code>public boolean isNull() { <START> return isNullResult; <END> }</code><technical_language>add || delegate.isNull()</technical_language>

Target:
public boolean isNull() { return isNullResult || delegate.isNull(); }
Source:
<code>public static void valueToJsonString( Value value, boolean extendedRoot, Type type, StringBuilder builder ) throws IOException { if ( value.hasChildren( JSONARRAY_KEY ) ) { valueVectorToJsonString( value.children().get( JSONARRAY_KEY ), builder, true, null ); return; } int size = value.children().size(); if ( size == 0 ) { if ( extendedRoot ) { builder.append( '{' ); if ( value.isDefined() ) { appendKeyColon( builder, ROOT_SIGN ); builder.append( nativeValueToJsonString( value ) ); } builder.append( '}' ); } else { builder.append( nativeValueToJsonString( value ) ); } } else { builder.append( '{' ); if ( value.isDefined() ) { appendKeyColon( builder, ROOT_SIGN ); builder.append( nativeValueToJsonString( value ) ); builder.append( ',' ); } <START> int i = 0; <END> for( Map.Entry<String, ValueVector> child : value.children().entrySet() ) { Type subType = null; appendKeyColon( builder, child.getKey() ); valueVectorToJsonString( child.getValue(), builder, false, subType ); if ( i++ < size - 1 ) { builder.append( ',' ); } } builder.append( '}' ); } }</code><technical_language>I changed this file recently, need pull? changes</technical_language>

Target:
public static void valueToJsonString( Value value, boolean extendedRoot, Type type, StringBuilder builder ) throws IOException { if ( value.hasChildren( JSONARRAY_KEY ) ) { valueVectorToJsonString( value.children().get( JSONARRAY_KEY ), builder, true, null ); return; } int size = value.children().size(); if ( size == 0 ) { if ( extendedRoot ) { builder.append( '{' ); if ( value.isDefined() ) { appendKeyColon( builder, ROOT_SIGN ); builder.append( nativeValueToJsonString( value ) ); } builder.append( '}' ); } else { builder.append( nativeValueToJsonString( value ) ); } } else { builder.append( '{' ); if ( value.isDefined() ) { appendKeyColon( builder, ROOT_SIGN ); builder.append( nativeValueToJsonString( value ) ); builder.append( ',' ); } int i = 0; for( Map.Entry<String, ValueVector> child : value.children().entrySet() ) { final Type subType = type.findSubType( child.getKey() ); appendKeyColon( builder, child.getKey() ); valueVectorToJsonString( child.getValue(), builder, false, subType ); if ( i++ < size - 1 ) { builder.append( ',' ); } } builder.append( '}' ); } }
Source:
<code>public void testSparkUDA() throws Exception { methodWatcher.execute("create derby aggregate string_concat for varchar(2000) external name 'com.splicemachine.tools.StringConcat'"); methodWatcher.execute("create table strings (v varchar(20))"); methodWatcher.execute("insert into strings values 'a','b','c','d'"); for (boolean useSpark : Arrays.asList(true, false)) { ResultSet rs = methodWatcher.executeQuery("select string_concat(v) from strings --splice-properties useSpark="+useSpark); Assert.assertTrue(rs.next()); String res = rs.getString(1); <START> Assert.assertTrue(res.contains("a")); <END> Assert.assertTrue(res.contains("b")); Assert.assertTrue(res.contains("c")); Assert.assertTrue(res.contains("d")); } }</code><technical_language>assertThat(res, allOf(containsString("a"), containsString("b"), containsString("c"), containsString("d"))) bring a error message</technical_language>

Target:
public void testSparkUDA() throws Exception { methodWatcher.execute("create derby aggregate string_concat for varchar(2000) external name 'com.splicemachine.tools.StringConcat'"); methodWatcher.execute("create table strings (v varchar(20))"); methodWatcher.execute("insert into strings values 'a','b','c','d'"); for (boolean useSpark : Arrays.asList(true, false)) { ResultSet rs = methodWatcher.executeQuery("select string_concat(v) from strings --splice-properties useSpark="+useSpark); Assert.assertTrue(rs.next()); String res = rs.getString(1); assertThat(res, allOf(containsString("a"), containsString("b"), containsString("c"), containsString("d"))); } }
Source:
<code><START> public void checkValidity() { <END> if (!(parent instanceof JThrowStatement)) { super.checkValidity(); } }</code><technical_language>I checkValidity() in JLiteral is wrong. more precise in checkValidity in JValueLiteral hierarchy</technical_language>

Target:
public void checkValidity() { if (!(parent instanceof JExpression || parent instanceof JThrowStatement || parent instanceof JNameValuePair || parent instanceof JReturnStatement || parent instanceof JFieldInitializer)) { super.checkValidity(); } }
Source:
<code>protected FileSystemElement createElement(FileSystemElement parent, Object fileSystemObject) throws InterruptedException { <START> if (parent == null) <END> parent = this.parent; return super.createElement(parent, fileSystemObject); }</code><technical_language>a local variable instead of reallocating argument, IMO</technical_language>

Target:
protected FileSystemElement createElement(FileSystemElement parent, Object fileSystemObject) throws InterruptedException { FileSystemElement element = (parent == null ? this.rootParent : parent); return super.createElement(element, fileSystemObject); }
Source:
<code>public TTLSet(Map<String,String> objectStrings) { super(); for (Entry<String,String> entry : objectStrings.entrySet()) { String column = entry.getKey(); <START> String ttl = entry.getValue(); <END> if (column.equals(NEGATE) && (ttl.isEmpty() || ttl.equalsIgnoreCase("true") || ttl.equalsIgnoreCase("false"))) { continue; } Long l = Long.parseLong(ttl); Pair<Text,Text> colPair = ColumnSet.decodeColumns(column); if (colPair.getSecond() == null) { addObject(colPair.getFirst(), l); } else { addObject(colPair.getFirst(), colPair.getSecond(), l); } } }</code><technical_language>I thinking case of ignoring whitespace also. trim do that. java String ttl = entry.getValue().trim();</technical_language>

Target:
public TTLSet(Map<String,String> objectStrings) { super(); for (Entry<String,String> entry : objectStrings.entrySet()) { String column = entry.getKey(); String ttl = entry.getValue().trim(); if (column.equals(NEGATE) && (ttl.isEmpty() || ttl.equalsIgnoreCase("true") || ttl.equalsIgnoreCase("false"))) { continue; } Long l = Long.parseLong(ttl); Pair<Text,Text> colPair = ColumnSet.decodeColumns(column); if (colPair.getSecond() == null) { addObject(colPair.getFirst(), l); } else { addObject(colPair.getFirst(), colPair.getSecond(), l); } } }
Source:
<code>private boolean hasTestAttribute(IClasspathEntry entry) { for (IClasspathAttribute a : entry.getExtraAttributes()) { <START> if ("test".equals(a.getName()) && "true".equals(a.getValue())) { <END> return true; } } return false; }</code><technical_language>WDYT Boolean.valueOf(a.getValue())? works ignoring case</technical_language>

Target:
private boolean hasTestAttribute(IClasspathEntry entry) { for (IClasspathAttribute a : entry.getExtraAttributes()) { if ("test".equals(a.getName()) && Boolean.valueOf(a.getValue())) { return true; } } return false; }
Source:
<code>static TreeArtifactValue create(Map<TreeFileArtifact, FileArtifactValue> childFileValues) { Map<String, FileArtifactValue> digestBuilder = Maps.newHashMapWithExpectedSize(childFileValues.size()); boolean isRemote = true; for (Map.Entry<TreeFileArtifact, FileArtifactValue> e : childFileValues.entrySet()) { <START> isRemote = isRemote && e.getValue().isRemote(); <END> digestBuilder.put(e.getKey().getParentRelativePath().getPathString(), e.getValue()); } return new TreeArtifactValue( DigestUtils.fromMetadata(digestBuilder).getDigestBytesUnsafe(), ImmutableMap.copyOf(childFileValues), isRemote); }</code><technical_language>happen? A TreeArtifact created piece action. happen parts of materialized</technical_language>

Target:
static TreeArtifactValue create(Map<TreeFileArtifact, FileArtifactValue> childFileValues) { Map<String, FileArtifactValue> digestBuilder = Maps.newHashMapWithExpectedSize(childFileValues.size()); Boolean isRemote = null; for (Map.Entry<TreeFileArtifact, FileArtifactValue> e : childFileValues.entrySet()) { FileArtifactValue v = e.getValue(); if (isRemote == null) { isRemote = v.isRemote(); } Preconditions.checkArgument(v.isRemote() == isRemote, "files in a tree artifact must either" + " be all remote or all local."); digestBuilder.put(e.getKey().getParentRelativePath().getPathString(), v); } return new TreeArtifactValue( DigestUtils.fromMetadata(digestBuilder).getDigestBytesUnsafe(), ImmutableMap.copyOf(childFileValues), isRemote != null ? isRemote : false); }
Source:
<code>public boolean hasTaskChanged(TaskRepository taskRepository, ITask task, TaskData taskData) { <START> if (taskData.isPartial() && task.getCreationDate() != null) { <END> return false; } String lastKnownMod = task.getAttribute(BugzillaRestTaskSchema.getDefault().DATE_MODIFICATION.getKey()); TaskAttribute attrModification = taskData.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION); if (attrModification != null && attrModification.getValue() != null && attrModification.getValue().equals(lastKnownMod)) { return false; } return true; }</code><technical_language>explain this logic? partial task data carry updated date/revision information</technical_language>

Target:
public boolean hasTaskChanged(TaskRepository taskRepository, ITask task, TaskData taskData) { String lastKnownLocalModValue = task .getAttribute(BugzillaRestTaskSchema.getDefault().DATE_MODIFICATION.getKey()); TaskAttribute latestRemoteModAttribute = taskData.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION); String latestRemoteModValue = latestRemoteModAttribute != null ? latestRemoteModAttribute.getValue() : null; return !Objects.equal(latestRemoteModValue, lastKnownLocalModValue); }
Source:
<code>private void updateTable() { _loadingIcon.setVisible(true); _table.setVisible(false); if (_query != null) { if (_pageSize > 0) { _query.setMaxRows(_pageSize); } } new SwingWorker<TableModel, Void>() { protected TableModel doInBackground() throws Exception { return _tableModelCallable.call(); }; protected void done() { try { TableModel tableModel = get(); _table.setModel(tableModel); final int columnCount = _table.getColumnCount(); if (columnCount > 10) { _table.setHorizontalScrollEnabled(true); } updatePagingButtons(); _loadingIcon.setVisible(false); _table.setVisible(true); } catch (Throwable e) { e = ErrorUtils.unwrapForPresentation(e); logger.error("Unexpected error occurred while building DataSetWindow contents", e); DataSetWindow.this.dispose(); WidgetUtils.showErrorMessage("Unexpected error", <START> "An unexpected error occurred while building data set. See logs for details." + e.getMessage()); <END> } }; }.execute(); }</code><technical_language>This error message is deliberately showing exception message _anything_. reintroducing is good - hidden user users want a techical message thrown in head anyway. Besides - missing a space else append dot ;-)</technical_language>

Target:
private void updateTable() { _loadingIcon.setVisible(true); _table.setVisible(false); if (_query != null) { if (_pageSize > 0) { _query.setMaxRows(_pageSize); } } new SwingWorker<TableModel, Void>() { protected TableModel doInBackground() throws Exception { return _tableModelCallable.call(); }; protected void done() { try { TableModel tableModel = get(); _table.setModel(tableModel); final int columnCount = _table.getColumnCount(); if (columnCount > 10) { _table.setHorizontalScrollEnabled(true); } updatePagingButtons(); _loadingIcon.setVisible(false); _table.setVisible(true); } catch (Throwable e) { e = ErrorUtils.unwrapForPresentation(e); logger.error("Unexpected error occurred while building DataSetWindow contents", e); DataSetWindow.this.dispose(); WidgetUtils.showErrorMessage("Unexpected error", "An unexpected error occurred while building data set. See logs for details."); } }; }.execute(); }
Source:
<code>private Command createCommandFromString(Item item, String commandAsString) throws BindingConfigParseException { <START> List<Class<? extends Command>> acceptedType = new ArrayList<Class<? extends Command>>(); <END> if(item!=null) { acceptedType = item.getAcceptedCommandTypes(); } else { acceptedType.add(StringType.class); } Command command = TypeParser.parseCommand(acceptedType, commandAsString); if (command == null) { throw new BindingConfigParseException("couldn't create Command from '" + commandAsString + "' "); } return command; }</code><technical_language>"acceptedType" is of type list i suggest rename "acceptedTypes"</technical_language>

Target:
private Command createCommandFromString(Item item, String commandAsString) throws BindingConfigParseException { List<Class<? extends Command>> acceptedTypes = new ArrayList<Class<? extends Command>>(); if(item!=null) { acceptedTypes = item.getAcceptedCommandTypes(); } else { acceptedTypes.add(StringType.class); } Command command = TypeParser.parseCommand(acceptedTypes, commandAsString); if (command == null) { throw new BindingConfigParseException("couldn't create Command from '" + commandAsString + "' "); } return command; }
Source:
<code>public Optional<PlayingData> createFrom(DataHolder dataHolder) { final boolean isPlaying; <START> if(supports(dataHolder)) { <END> isPlaying = ((EntityVillager) dataHolder).isPlaying(); return Optional.of(new SpongePlayingData(isPlaying)); } return Optional.empty(); }</code><technical_language>space if</technical_language>

Target:
public Optional<PlayingData> createFrom(DataHolder dataHolder) { if (supports(dataHolder)) { final boolean isPlaying = ((EntityVillager) dataHolder).isPlaying(); return Optional.of(new SpongePlayingData(isPlaying)); } return Optional.empty(); }
Source:
<code>public ParallelIndexTuningConfig withPartitionsSpec(PartitionsSpec partitionsSpec) { <START> return new ParallelIndexTuningConfig( null, null, getMaxRowsInMemory(), getMaxBytesInMemory(), null, null, splitHintSpec, partitionsSpec, getIndexSpec(), getIndexSpecForIntermediatePersists(), getMaxPendingPersists(), isForceGuaranteedRollup(), isReportParseExceptions(), getPushTimeout(), getSegmentWriteOutMediumFactory(), null, maxNumConcurrentSubTasks, maxRetry, taskStatusCheckPeriodMs, chatHandlerTimeout, chatHandlerNumRetries, maxNumSegmentsToMerge, totalNumMergeTasks, isLogParseExceptions(), getMaxParseExceptions(), getMaxSavedParseExceptions() ); <END> }</code><technical_language>Possibly consistent getters for parameters direct access for</technical_language>

Target:
public ParallelIndexTuningConfig withPartitionsSpec(PartitionsSpec partitionsSpec) { return new ParallelIndexTuningConfig( null, null, getMaxRowsInMemory(), getMaxBytesInMemory(), null, null, getSplitHintSpec(), partitionsSpec, getIndexSpec(), getIndexSpecForIntermediatePersists(), getMaxPendingPersists(), isForceGuaranteedRollup(), isReportParseExceptions(), getPushTimeout(), getSegmentWriteOutMediumFactory(), null, getMaxNumConcurrentSubTasks(), getMaxRetry(), getTaskStatusCheckPeriodMs(), getChatHandlerTimeout(), getChatHandlerNumRetries(), getMaxNumSegmentsToMerge(), getTotalNumMergeTasks(), isLogParseExceptions(), getMaxParseExceptions(), getMaxSavedParseExceptions() ); }
Source:
<code>public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryAsObservable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); final TestSubscriber<TestItem> testSubscriber = new TestSubscriber<TestItem>(); storIOSQLite .get() .object(TestItem.class) .withQuery(RawQuery.builder().query("test query").build()) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); assertThat(testSubscriber.getOnErrorEvents().get(0)) .isInstanceOf(StorIOException.class) <START> .hasCauseInstanceOf(IllegalStateException.class); <END> verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).rawQuery(any(RawQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal); }</code><technical_language>Exception message</technical_language>

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryAsObservable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); final TestSubscriber<TestItem> testSubscriber = new TestSubscriber<TestItem>(); storIOSQLite .get() .object(TestItem.class) .withQuery(RawQuery.builder().query("test query").build()) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); assertThat(testSubscriber.getOnErrorEvents().get(0)) .isInstanceOf(StorIOException.class) .hasCauseInstanceOf(IllegalStateException.class) .hasMessageEndingWith("This type does not have type mapping: " + "type = " + TestItem.class + "," + "db was not touched by this operation, please add type mapping for this type"); verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).rawQuery(any(RawQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal); }
Source:
<code>private static FieldInfo getIterableFieldInfo(ClassInfo classInfo, Class<?> parameterType, String relationshipType, Direction relationshipDirection, boolean strict) { List<FieldInfo> fieldInfos = classInfo .findIterableFields(parameterType, relationshipType, relationshipDirection, strict); if (fieldInfos.size() == 0) { if (!strict) { fieldInfos = classInfo.findIterableFields(parameterType); } } if (fieldInfos.size() == 1) { FieldInfo candidateFieldInfo = fieldInfos.iterator().next(); if (candidateFieldInfo.hasAnnotation(Relationship.class)) { AnnotationInfo relationshipAnnotation = candidateFieldInfo.getAnnotations().get(Relationship.class); if (!relationshipType.equals(relationshipAnnotation.get(Relationship.TYPE, null))) { return null; } } <START> if (relationshipDirection.equals(Direction.INCOMING) && <END> (candidateFieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.INCOMING)) || (candidateFieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.UNDIRECTED))) { return candidateFieldInfo; } if (!relationshipDirection.equals(Direction.INCOMING) && !candidateFieldInfo .relationshipDirectionOrDefault(Direction.OUTGOING).equals(Direction.INCOMING)) { return candidateFieldInfo; } } if (fieldInfos.size() > 0) { LOGGER.warn("Cannot map iterable of to instance of {}. More than one potential matching field found.", parameterType, classInfo.name()); } return null; }</code><technical_language>Please ==</technical_language>

Target:
private static FieldInfo getIterableFieldInfo(ClassInfo classInfo, Class<?> parameterType, String relationshipType, Direction relationshipDirection, boolean strict) { List<FieldInfo> fieldInfos = classInfo .findIterableFields(parameterType, relationshipType, relationshipDirection, strict); if (fieldInfos.size() == 0) { if (!strict) { fieldInfos = classInfo.findIterableFields(parameterType); } } if (fieldInfos.size() == 1) { FieldInfo candidateFieldInfo = fieldInfos.iterator().next(); if (candidateFieldInfo.hasAnnotation(Relationship.class)) { AnnotationInfo relationshipAnnotation = candidateFieldInfo.getAnnotations().get(Relationship.class); if (!relationshipType.equals(relationshipAnnotation.get(Relationship.TYPE, null))) { return null; } } if (relationshipDirection == Direction.INCOMING && candidateFieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING) == Direction.INCOMING || candidateFieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING) == Direction.UNDIRECTED) { return candidateFieldInfo; } if (relationshipDirection != Direction.INCOMING && candidateFieldInfo .relationshipDirectionOrDefault(Direction.OUTGOING) != Direction.INCOMING) { return candidateFieldInfo; } } if (fieldInfos.size() > 0) { LOGGER.warn("Cannot map iterable of to instance of {}. More than one potential matching field found.", parameterType, classInfo.name()); } return null; }
Source:
<code>public <START> KafkaPoller(Consumer<String, <END> ChangeEvent> consumer, Uris uris, Instant firstStartTime, int batchSize, Collection<String> topics, RdfRepository rdfRepo) { this.consumer = consumer; this.uris = uris; this.firstStartTime = firstStartTime; this.batchSize = batchSize; this.topics = topics; this.rdfRepo = rdfRepo; try { this.root = uris.builder().build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } }</code><technical_language>Constructor is traditionally method of a class. (feel free ignore)</technical_language>

Target:
public KafkaPoller(Consumer<String, ChangeEvent> consumer, Uris uris, Instant firstStartTime, int batchSize, Collection<String> topics, RdfRepository rdfRepo) { this.consumer = consumer; this.uris = uris; this.firstStartTime = firstStartTime; this.batchSize = batchSize; this.topics = topics; this.rdfRepo = rdfRepo; try { this.root = uris.builder().build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } this.topicPartitions = setUpTopicPartitions(); }
Source:
<code>public void reset() { <START> final int usedBufferCapacity = usedFlagBuffer.capacity(); <END> final int n = usedBufferCapacity / 8; for (int i = 0; i < n; i += 8) { usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } }</code><technical_language>Suggested extract a static utility function zeroOut(ByteBuffer)</technical_language>

Target:
public void reset() { final int usedFlagBufferCapacity = usedFlagBuffer.capacity(); final int n = (usedFlagBufferCapacity / Long.BYTES) * Long.BYTES; for (int i = 0; i < n; i += Long.BYTES) { usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } }
Source:
<code>DefaultClusteringService(final ClusteringServiceConfiguration configuration) { this.configuration = configuration; URI ehcacheUri = configuration.getClusterUri(); <START> this.properties = configuration.getProperties(); <END> this.clusterUri = extractClusterUri(ehcacheUri); this.entityIdentifier = clusterUri.relativize(ehcacheUri).getPath(); this.timeouts = configuration.getTimeouts(); }</code><technical_language>problem is timeout is coming another place (that override this). I properties coming places. I answer I a good idea</technical_language>

Target:
DefaultClusteringService(final ClusteringServiceConfiguration configuration) { this.configuration = configuration; URI ehcacheUri = configuration.getClusterUri(); this.clusterUri = extractClusterUri(ehcacheUri); this.entityIdentifier = clusterUri.relativize(ehcacheUri).getPath(); this.timeouts = configuration.getTimeouts(); this.properties = configuration.getProperties(); }
Source:
<code>public TestConstraintSolverStrategy(boolean consolidatedConfigFlag) { this.consolidatedConfigFlag = consolidatedConfigFlag; <START> LOG.info("Running tests with consolidatedConfigFlag={}", ""+consolidatedConfigFlag); <END> }</code><technical_language>""+ necessary</technical_language>

Target:
public TestConstraintSolverStrategy(boolean consolidatedConfigFlag) { this.consolidatedConfigFlag = consolidatedConfigFlag; LOG.info("Running tests with consolidatedConfigFlag={}", consolidatedConfigFlag); }
Source:
<code>public ResponseEntity<?> getCurrentBanner() { Banner currentBanner = bannerService.getCurrentbanner(); <START> return new ResponseEntity<>(currentBanner, HttpStatus.OK); <END> }</code><technical_language>createResponseEntity() helper method below</technical_language>

Target:
public ResponseEntity<?> getCurrentBanner() { Banner currentBanner = bannerService.getCurrentbanner(); return createResponseEntity(HttpStatus.OK, "Found a corresponding banner.", currentBanner); }
Source:
<code>public Object execute(Object[] parameters) { KeyValueQuery<?> query = prepareQuery(parameters); if (this.isCount) { final Class<?> javaType = queryMethod.getEntityInformation().getJavaType(); if (this.isDistinct) { final Iterable<?> iterable = this.keyValueOperations.find(query, javaType); return StreamUtils.createStreamFromIterator(iterable.iterator()).distinct().count(); } else { return this.keyValueOperations.count(query, javaType); } } if (this.isDelete) { return this.executeDeleteQuery(query, queryMethod); } if (this.isExists) { <START> final long count = this.keyValueOperations.count(query, queryMethod.getEntityInformation().getJavaType()); <END> return count > 0; } if (queryMethod.isPageQuery() || queryMethod.isSliceQuery()) { return this.executePageSliceQuery(parameters, query, queryMethod); } if (queryMethod.isCollectionQuery() || queryMethod.isQueryForEntity() || queryMethod.isStreamQuery()) { return this.executeFindQuery(query, queryMethod, this.isDistinct); } String message = String.format("Query method '%s' not supported.", queryMethod.getName()); throw new UnsupportedOperationException(message); }</code><technical_language>main reason exists exists is able differentiate count. count operation needs find items matching query exists needs find return result immediately. So, need find a performing implementation, structure good</technical_language>

Target:
public Object execute(Object[] parameters) { KeyValueQuery<?> query = prepareQuery(parameters); if (this.isCount) { final Class<?> javaType = queryMethod.getEntityInformation().getJavaType(); if (this.isDistinct) { final Iterable<?> iterable = this.keyValueOperations.find(query, javaType); return StreamUtils.createStreamFromIterator(iterable.iterator()).distinct().count(); } else { return this.keyValueOperations.count(query, javaType); } } if (this.isDelete) { return this.executeDeleteQuery(query, queryMethod); } if (this.isExists) { query.setOffset(0); query.setRows(1); final Iterable<?> result = this.keyValueOperations.find(query, queryMethod.getEntityInformation().getJavaType()); return result.iterator().hasNext(); } if (queryMethod.isPageQuery() || queryMethod.isSliceQuery()) { return this.executePageSliceQuery(parameters, query, queryMethod); } if (queryMethod.isCollectionQuery() || queryMethod.isQueryForEntity() || queryMethod.isStreamQuery()) { return this.executeFindQuery(query, queryMethod, this.isDistinct); } String message = String.format("Query method '%s' not supported.", queryMethod.getName()); throw new UnsupportedOperationException(message); }
Source:
<code>public void lock() { this.lock.lock(); synchronized (DiskRepository.this) { int count = readLockCount.get(); assert count >= 0; if (lockFileChannel != null && count == 0) { try { fileLock = lockFileChannel.lock(0, 1, true); } catch (IOException ioe) { LOGGER.warn(ioe, DiskConnectorI18n.problemAcquiringFileLock, getSourceName()); } } readLockCount.getAndIncrement(); <START> } <END> }</code><technical_language>synchronized block a try-catch-finally? If exception this block, hold ReadWriteLock's lock. cleaned elsewhere</technical_language>

Target:
public void lock() { this.lock.lock(); if (lockFileChannel != null) { try { synchronized (DiskRepository.this) { int count = readLockCount.get(); assert count >= 0; if (count == 0) { fileLock = lockFileChannel.lock(0, 1, true); } readLockCount.getAndIncrement(); } } catch (Throwable t) { this.lock.unlock(); I18n msg = DiskConnectorI18n.problemAcquiringFileLock; throw new IllegalStateException(msg.text(DiskRepository.this.getSourceName()), t); } } }
Source:
<code>public QueryHandleWithResultSet executePrepare(GrillSessionHandle sessionHandle, QueryPrepareHandle prepareHandle, long timeoutMillis, GrillConf conf, String queryName) throws GrillException { try { LOG.info("ExecutePrepare: " + sessionHandle.toString() + " query:" + prepareHandle.getPrepareHandleId() + " timeout:" + timeoutMillis); acquire(sessionHandle); PreparedQueryContext pctx = getPreparedQueryContext(sessionHandle, prepareHandle); Configuration qconf = getGrillConf(sessionHandle, conf); QueryContext ctx = createContext(pctx, getSession(sessionHandle).getUserName(), conf, qconf); <START> if (StringUtils.isNotBlank(queryName)) { <END> ctx.setQueryName(queryName); } return executeTimeoutInternal(sessionHandle, ctx, timeoutMillis, qconf); } finally { release(sessionHandle); } }</code><technical_language>set queryname prepared query name</technical_language>

Target:
public QueryHandleWithResultSet executePrepare(GrillSessionHandle sessionHandle, QueryPrepareHandle prepareHandle, long timeoutMillis, GrillConf conf, String queryName) throws GrillException { try { LOG.info("ExecutePrepare: " + sessionHandle.toString() + " query:" + prepareHandle.getPrepareHandleId() + " timeout:" + timeoutMillis); acquire(sessionHandle); PreparedQueryContext pctx = getPreparedQueryContext(sessionHandle, prepareHandle); Configuration qconf = getGrillConf(sessionHandle, conf); QueryContext ctx = createContext(pctx, getSession(sessionHandle).getUserName(), conf, qconf); if (StringUtils.isNotBlank(queryName)) { ctx.setQueryName(queryName); } else { ctx.setQueryName(pctx.getQueryName()); } return executeTimeoutInternal(sessionHandle, ctx, timeoutMillis, qconf); } finally { release(sessionHandle); } }
Source:
<code>public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { String message = "Remove this null-check of an \"Optional\"."; <START> if (isComparisonOperator(binaryExpression.operatorToken())) { <END> ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if (isOptional(left) && isNull(right) || isNull(left) && isOptional(right)) { context.reportIssue(this, binaryExpression, message); } } super.visitBinaryExpression(binaryExpression); }</code><technical_language>I prefer simply check kind of binaryExpression, this information is provided syntax tree: binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)</technical_language>

Target:
public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { if (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)) { ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if ((isOptional(left) && isNull(right)) || (isNull(left) && isOptional(right))) { context.reportIssue(this, binaryExpression, "Remove this null-check of an \"Optional\"."); } } super.visitBinaryExpression(binaryExpression); }
Source:
<code>public static Map<String, Set<String>> getTagsFromGlobalTags() { final String globalTags = getDatadogGlobalDescriptor().getGlobalTags(); Map<String, Set<String>> tags = new HashMap<>(); List<String> globalTagsLines = DatadogUtilities.linesToList(globalTags); for (String globalTagsLine : globalTagsLines) { List<String> tagList = DatadogUtilities.cstrToList(globalTagsLine); if (tagList.isEmpty()) { continue; } for(int i = 0; i < tagList.size(); i++) { <START> String[] tagItem = tagList.get(i).replaceAll(" ", "").split(":"); <END> if(tagItem.length == 2) { String tagName = tagItem[0]; String tagValue = tagItem[1]; Set<String> tagValues = tags.containsKey(tagName) ? tags.get(tagName) : new HashSet<String>(); tagValues.add(tagValue.toLowerCase()); tags.put(tagName, tagValues); } else if(tagItem.length == 1) { String tagName = tagItem[0]; Set<String> tagValues = tags.containsKey(tagName) ? tags.get(tagName) : new HashSet<String>(); tagValues.add(""); tags.put(tagName, tagValues); } else { logger.fine(String.format("Ignoring the tag %s. It is empty.", tagItem)); } } } return tags; }</code><technical_language>suggestion String[] tagItem = tagList.get(i).replaceAll(" ", "").split(":", 2);</technical_language>

Target:
public static Map<String, Set<String>> getTagsFromGlobalTags() { final String globalTags = getDatadogGlobalDescriptor().getGlobalTags(); Map<String, Set<String>> tags = new HashMap<>(); List<String> globalTagsLines = DatadogUtilities.linesToList(globalTags); for (String globalTagsLine : globalTagsLines) { List<String> tagList = DatadogUtilities.cstrToList(globalTagsLine); if (tagList.isEmpty()) { continue; } for (int i = 0; i < tagList.size(); i++) { String[] tagItem = tagList.get(i).replaceAll(" ", "").split(":", 2); if(tagItem.length == 2) { String tagName = tagItem[0]; String tagValue = tagItem[1]; Set<String> tagValues = tags.containsKey(tagName) ? tags.get(tagName) : new HashSet<String>(); tagValues.add(tagValue.toLowerCase()); tags.put(tagName, tagValues); } else if(tagItem.length == 1) { String tagName = tagItem[0]; Set<String> tagValues = tags.containsKey(tagName) ? tags.get(tagName) : new HashSet<String>(); tagValues.add(""); tags.put(tagName, tagValues); } else { logger.fine(String.format("Ignoring the tag %s. It is empty.", tagItem)); } } } return tags; }