auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AvroRecordIterator(Schema schema, ByteString bytes) { reader = new GenericDatumReader<>(schema); <START> in = new DecoderFactory().binaryDecoder(bytes.toByteArray(), null); <END> }</code><technical_language>conf is used</technical_language>

Target:
AvroRecordIterator(Schema schema, ByteString bytes) { reader = new GenericDatumReader<>(schema); in = new DecoderFactory().binaryDecoder(bytes.toByteArray(), null); }
Source:
<code>public static void processResponse(HttpResponseProcessor responseProcessor, int responseCode, ResponseStreamAccessor streamAccessor) { if (responseCode >= 200 && responseCode < 300) { InputStream responseStream; try { responseStream = streamAccessor.getResponseStream(); } catch (IOException e) { <START> responseProcessor.handleException(e); <END> return; } responseProcessor.processSuccess(responseCode, responseStream); } else if (responseCode >= 400 && responseCode < 500) { responseProcessor.processClientError(responseCode); } else if (responseCode >= 500 && responseCode < 600) { responseProcessor.processServerError(responseCode); } else { responseProcessor.processOther(responseCode); } }</code><technical_language>Is a specific reason eliminated specific exception typing response processor? I in abstract sense, blurring IOException untyped Exception a bad thing</technical_language>

Target:
public static void processResponse(HttpResponseProcessor responseProcessor, int responseCode, ResponseStreamAccessor streamAccessor) { if (responseCode >= 200 && responseCode < 300) { InputStream responseStream; try { responseStream = streamAccessor.getResponseStream(); } catch (IOException e) { responseProcessor.handleIOException(e); return; } responseProcessor.processSuccess(responseCode, responseStream); } else if (responseCode >= 400 && responseCode < 500) { responseProcessor.processClientError(responseCode); } else if (responseCode >= 500 && responseCode < 600) { responseProcessor.processServerError(responseCode); } else { responseProcessor.processOther(responseCode); } }
Source:
<code>protected boolean doesDataExist(Entity entity) { <START> return !entity.isDead; <END> }</code><technical_language>data exists if entity is dead</technical_language>

Target:
protected boolean doesDataExist(Entity entity) { return true; }
Source:
<code>public void clear() throws SQLException { dbmsSynchronizer.closeSharedDatabase(); <START> this.dbmsConnection.getConnection().close(); <END> }</code><technical_language>remove this statement dbmsSynchronizer connection, it</technical_language>

Target:
public void clear() throws SQLException { dbmsSynchronizer.closeSharedDatabase(); }
Source:
<code>private void registerSnomedIdentifierService(final SnomedIdentifierConfiguration conf, final Environment env, final ISnomedIdentiferReservationService reservationService) { ISnomedIdentifierService identifierService = null; switch (conf.getStrategy()) { case EMBEDDED: <START> final Index index = Indexes.createIndex("snomedids", env.service(ObjectMapper.class), new Mappings(SctId.class), env.service(IndexSettings.class)); <END> index.admin().create(); LOGGER.info("Snow Owl is configured to use embedded identifier service."); final ItemIdGenerationStrategy generationStrategy = new SequentialItemIdGenerationStrategy(index, reservationService); identifierService = new DefaultSnomedIdentifierService(index, generationStrategy, reservationService, conf); break; case CIS: final ObjectMapper mapper = new ObjectMapper(); LOGGER.info("Snow Owl is configured to use CIS based identifier service."); identifierService = new CisSnomedIdentifierService(conf, reservationService, mapper); break; default: throw new IllegalStateException(String.format("Unknown ID generation source configured: %s. ", conf.getStrategy())); } env.services().registerService(ISnomedIdentifierService.class, identifierService); }</code><technical_language>nice index name a constant</technical_language>

Target:
private void registerSnomedIdentifierService(final SnomedIdentifierConfiguration conf, final Environment env, final ISnomedIdentiferReservationService reservationService) { ISnomedIdentifierService identifierService = null; switch (conf.getStrategy()) { case EMBEDDED: final Index index = Indexes.createIndex(SNOMED_IDS_INDEX, env.service(ObjectMapper.class), new Mappings(SctId.class), env.service(IndexSettings.class)); index.admin().create(); final ItemIdGenerationStrategy generationStrategy = new SequentialItemIdGenerationStrategy(index, reservationService); identifierService = new DefaultSnomedIdentifierService(index, generationStrategy, reservationService, conf); break; case CIS: final ObjectMapper mapper = new ObjectMapper(); identifierService = new CisSnomedIdentifierService(conf, reservationService, mapper); break; default: throw new IllegalStateException(String.format("Unknown ID generation source configured: %s. ", conf.getStrategy())); } env.services().registerService(ISnomedIdentifierService.class, identifierService); LOGGER.info("Snow Owl is configured to use based identifier service.", conf.getStrategy()); }
Source:
<code>public String say(long number) { if (number < 0) { throw new IllegalArgumentException("input out of range"); } <START> char[] digits = String.valueOf(number).toCharArray(); <END> if (digits.length > 12) { throw new IllegalArgumentException("input out of range"); } char[][] processedDigits = process(digits); String message = ""; for (int index = 0; index < processedDigits.length; index++) { char[] blockDigits = processedDigits[index]; message = concatWithSpace(message, sayDigits(blockDigits, processedDigits.length - index)); } return message; }</code><technical_language>processing a list of characters, turn input number a long extract numbers numeric operations (eg. integer division modulo)? This rid of leading zeros problem address multiple times in this solution</technical_language>

Target:
public String say(long number) { if (number < 0 || number >= Magnitude.TRILLIONS.getNumber()) { throw new IllegalArgumentException("input out of range"); } List<Part> parts = new ArrayList<Say.Part>(); for (Magnitude magnitude: supportedMagnitudes) { double quoziente = Math.floor(number / magnitude.getNumber()); Part part = new Part((int) quoziente, magnitude); if (part.getDigits() > 0 || (part.getMagnitude().equals(Magnitude.ONES) && parts.size() == 0)) { parts.add(part); } number = number % magnitude.getNumber(); } return String.join(" ", parts.stream().map(part -> part.say()).collect(Collectors.toList())); }
Source:
<code>public String getHARole() { <START> if (true) return roles.keySet().toString(); END> if ( roles.containsKey( HighAvailabilityModeSwitcher.MASTER ) ) { return HighAvailabilityModeSwitcher.MASTER; } if ( roles.containsKey( HighAvailabilityModeSwitcher.SLAVE ) ) { return HighAvailabilityModeSwitcher.SLAVE; } return HighAvailabilityModeSwitcher.UNKNOWN; }</code><technical_language>I address this TODO</technical_language>

Target:
public String getHARole() { if ( roles.containsKey( HighAvailabilityModeSwitcher.MASTER ) ) { return HighAvailabilityModeSwitcher.MASTER; } if ( roles.containsKey( HighAvailabilityModeSwitcher.SLAVE ) ) { return HighAvailabilityModeSwitcher.SLAVE; } return HighAvailabilityModeSwitcher.UNKNOWN; }
Source:
<code>public void refreshPersonDetails() { if (!isAdded()) return; Person person = loadPerson(); if (person != null) { <START> int avatarSz = getResources().getDimensionPixelSize(R.dimen.avatar_sz_large); <END> String avatarUrl = GravatarUtils.fixGravatarUrl(person.getAvatarUrl(), avatarSz); mAvatarImageView.setImageUrl(avatarUrl, WPNetworkImageView.ImageType.AVATAR); mDisplayNameTextView.setText(person.getDisplayName()); mUsernameTextView.setText(person.getUsername()); mRoleTextView.setText(StringUtils.capitalize(person.getRole())); setupRoleContainerForCapability(); } else { AppLog.w(AppLog.T.PEOPLE, "Person returned null from DB for personID: " + mPersonID + " & localTableBlogID: " + mLocalTableBlogID); } }</code><technical_language>This match size in layout, is people_avatar_sz</technical_language>

Target:
public void refreshPersonDetails() { if (!isAdded()) return; Person person = loadPerson(); if (person != null) { int avatarSz = getResources().getDimensionPixelSize(R.dimen.people_avatar_sz); String avatarUrl = GravatarUtils.fixGravatarUrl(person.getAvatarUrl(), avatarSz); mAvatarImageView.setImageUrl(avatarUrl, WPNetworkImageView.ImageType.AVATAR); mDisplayNameTextView.setText(person.getDisplayName()); mUsernameTextView.setText(person.getUsername()); mRoleTextView.setText(StringUtils.capitalize(person.getRole())); setupRoleContainerForCapability(); } else { AppLog.w(AppLog.T.PEOPLE, "Person returned null from DB for personID: " + mPersonID + " & localTableBlogID: " + mLocalTableBlogID); } }
Source:
<code>public void shouldReturnAllEmailRecordsWhenNoFiltersSet() { when(auditService.countEmailRecords(any(EmailRecordSearchCriteria.class))).thenReturn(88L); EmailRecords<? extends BasicEmailRecordDto> records = emailController.getEmails(new GridSettings(), request); <START> assertEquals(Integer.valueOf(1), records.getPage()); <END> assertEquals(Integer.valueOf(88), records.getRecords()); assertEquals(Integer.valueOf(9), records.getTotal()); ArgumentCaptor<EmailRecordSearchCriteria> captor = ArgumentCaptor.forClass(EmailRecordSearchCriteria.class); verify(auditService).findEmailRecords(captor.capture()); }</code><technical_language>Integer.valueOf is redundant, unboxing/boxing do work</technical_language>

Target:
public void shouldReturnAllEmailRecordsWhenNoFiltersSet() { when(auditService.countEmailRecords(any(EmailRecordSearchCriteria.class))).thenReturn(88L); EmailRecords<? extends BasicEmailRecordDto> records = emailController.getEmails(new GridSettings(), request); assertEquals(Integer.valueOf(1), records.getPage()); assertEquals(Integer.valueOf(88), records.getRecords()); assertEquals(Integer.valueOf(9), records.getTotal()); }
Source:
<code>static Object getValue(JsonNode value) { if (value.isValueNode()) { switch (value.getNodeType()) { case BOOLEAN: return value.asBoolean(); case NUMBER: if (value.isInt()) { return value.asInt(); } else if (value.isLong()) { return value.asLong(); } else if (value.isDouble()) { return value.asDouble(); } <START> break; <END> case STRING: return value.asText(); default: throw new IllegalStateException("Unexpected value: " + value.getNodeType()); } } return value; }</code><technical_language>instead of break, return here? I more clear. add a else block end, return else condition</technical_language>

Target:
static Object getValue(JsonNode value) { if (value.isValueNode()) { switch (value.getNodeType()) { case BOOLEAN: return value.asBoolean(); case NUMBER: if (value.isInt()) { return value.asInt(); } else if (value.isLong()) { return value.asLong(); } else if (value.isDouble()) { return value.asDouble(); } else{ return value; } case STRING: return value.asText(); default: throw new IllegalStateException("Unexpected value: " + value.getNodeType()); } } return value; }
Source:
<code>private boolean showPermissionRequestPromptOnAndroid10IfNeeded(boolean wifiFilterEnabled) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { return false; } <START> final PreferenceScreen prefScreen = getPreferenceScreen(); <END> if (prefPermissionRequestPromptOnAndroid10 != null) { prefScreen.removePreference(prefPermissionRequestPromptOnAndroid10); prefPermissionRequestPromptOnAndroid10 = null; } if (hasLocationPermission()) { return false; } if (!wifiFilterEnabled) { return true; } Preference pref = new Preference(requireActivity()); pref.setKey(PREF_KEY_PERMISSION_REQUEST_PROMPT); pref.setTitle(R.string.autodl_wifi_filter_permission_title); pref.setSummary(R.string.autodl_wifi_filter_permission_message); pref.setIcon(R.drawable.ic_warning_red); pref.setOnPreferenceClickListener(preference -> { requestLocationPermission(); return true; }); pref.setPersistent(false); getPreferenceScreen().addPreference(pref); prefPermissionRequestPromptOnAndroid10 = pref; return true; }</code><technical_language>This is single time in if below. method there</technical_language>

Target:
private boolean showPermissionRequestPromptOnAndroid10IfNeeded(boolean wifiFilterEnabled) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { return false; } if (prefPermissionRequestPromptOnAndroid10 != null) { getPreferenceScreen().removePreference(prefPermissionRequestPromptOnAndroid10); prefPermissionRequestPromptOnAndroid10 = null; } if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { return false; } if (!wifiFilterEnabled) { return true; } Preference pref = new Preference(requireActivity()); pref.setKey(PREF_KEY_LOCATION_PERMISSION_REQUEST_PROMPT); pref.setTitle(R.string.autodl_wifi_filter_permission_title); pref.setSummary(R.string.autodl_wifi_filter_permission_message); pref.setIcon(R.drawable.ic_warning_red); pref.setOnPreferenceClickListener(preference -> { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE); return true; }); pref.setPersistent(false); getPreferenceScreen().addPreference(pref); prefPermissionRequestPromptOnAndroid10 = pref; return true; }
Source:
<code>public void assertDoesNotStartWith(AssertionInfo info, CharSequence actual, CharSequence prefix) { <START> if (prefix == null) throw new NullPointerException("The given prefix should not be null"); <END> assertNotNull(info, actual); if (comparisonStrategy.stringStartsWith(actual.toString(), prefix.toString())) throw failures.failure(info, shouldNotStartWith(actual, prefix, comparisonStrategy)); }</code><technical_language>extract method check prefix avoid duplicated code (assertStartsWith)</technical_language>

Target:
public void assertDoesNotStartWith(AssertionInfo info, CharSequence actual, CharSequence prefix) { failIfPrefixIsNull(prefix); assertNotNull(info, actual); if (comparisonStrategy.stringStartsWith(actual.toString(), prefix.toString())) throw failures.failure(info, shouldNotStartWith(actual, prefix, comparisonStrategy)); }
Source:
<code>public ACL getACL() { final ACL base = super.getACL(); return new ACL() { @Override public boolean hasPermission(Authentication a, Permission permission) { if (permission== Computer.CONFIGURE) return false; <START> return base.hasPermission(a,permission); <END> } }; }</code><technical_language>nonstandard formatting lines, FYI</technical_language>

Target:
public ACL getACL() { final ACL base = super.getACL(); return new ACL() { @Override public boolean hasPermission(Authentication a, Permission permission) { return permission == Computer.CONFIGURE ? false : base.hasPermission(a,permission); } }; }
Source:
<code>protected Iterable<Task> generateSubTasks( final String groupId, final Iterable<DataSegment> segments, final IndexSpec indexSpec, final boolean force, final boolean validate ) { return FunctionalIterable .create(segments) .keep( new Function<DataSegment, Task>() { <START> @Nullable <END> @Override public Task apply(DataSegment input) { return new SubTask(groupId, segment, indexSpec, force, validate); } } ); }</code><technical_language>nan</technical_language>

Target:
protected Iterable<Task> generateSubTasks( final String groupId, final Iterable<DataSegment> segments, final IndexSpec indexSpec, final boolean force, final boolean validate ) { return Iterables.transform( segments, new Function<DataSegment, Task>() { @Override public Task apply(DataSegment input) { return new SubTask(groupId, segment, indexSpec, force, validate); } } ); }
Source:
<code>public Object visit(ASTMethodOrConstructorDeclaration node, Object data) { <START> int cyclo = (int) Metrics.get(OperationMetricKey.NCSS, node); <END> if (cyclo >= methodReportLevel) { addViolation(data, node, new String[] {node instanceof ASTMethodDeclaration ? "method" : "constructor", node.getQualifiedName().getOperation(), "" + cyclo, }); } return data; }</code><technical_language>Call variable methodSize size..</technical_language>

Target:
public Object visit(ASTMethodOrConstructorDeclaration node, Object data) { int methodSize = (int) Metrics.get(OperationMetricKey.NCSS, node); if (methodSize >= methodReportLevel) { addViolation(data, node, new String[] {node instanceof ASTMethodDeclaration ? "method" : "constructor", node.getQualifiedName().getOperation(), "" + methodSize, }); } return data; }
Source:
<code>private static Options createOptions() { Options options = new Options(); <START> Option scriptPath = new Option(null, "scriptPath", true, "path to directory/jar for script(s) lookup"); <END> scriptPath.setRequired(true); Option control = new Option(null, "control", true, "location to listen for K3PO control connections"); Option verbose = new Option(null, "verbose", false, "verbose"); options.addOption(scriptPath); options.addOption(control); options.addOption(verbose); return options; }</code><technical_language>If this is for jars well, I case need multiple paths...</technical_language>

Target:
private static Options createOptions() { Options options = new Options(); Option scriptPath = new Option(null, "scriptpath", true, "Path(s) to directory/jar for script(s) lookup. Multiple entries should be separated by semicolon."); Option control = new Option(null, "control", true, "location to listen for K3PO control connections"); Option verbose = new Option(null, "verbose", false, "verbose"); Option version = new Option(null, "version", false, "version"); options.addOption(scriptPath); options.addOption(control); options.addOption(verbose); options.addOption(version); return options; }
Source:
<code>public void beforeTest() throws IOException { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); TEMPLATE_NAME = String.format( "projects/%s/locations/%s/jobTemplates/%s", PROJECT_NUMBER, LOCATION, TEMPLATE_ID); try { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); <START> } catch (GoogleJsonResponseException gjre) { } <END> bout.reset(); }</code><technical_language><LINK_0></technical_language>

Target:
public void beforeTest() throws IOException { originalOut = System.out; bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); TEMPLATE_NAME = String.format( "projects/%s/locations/%s/jobTemplates/%s", PROJECT_NUMBER, LOCATION, TEMPLATE_ID); DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); bout.reset(); }
Source:
<code>public void peopleMessage(final PeopleDescription peopleDescription) { try { <START> peopleDescription.getMessage().toString(); <END> final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); } catch (AssertionError e) { MPLog.e(LOGTAG, "Could not record people update (see <LINK_0>", e); } }</code><technical_language>normalized in MixpanelMessageDescription constructor</technical_language>

Target:
public void peopleMessage(final PeopleDescription peopleDescription) { final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); }
Source:
<code>public void testForceDeleteArtifactAllowed() throws Exception { final String artifactPath = "org/carlspring/strongbox/test-artifact-to-trash/1.1/test-artifact-to-trash-1.1.jar"; final File repositoryTrashDir = new File(BASEDIR + "/storages/storage0/releases/.trash"); final File repositoryDir = new File(BASEDIR + "/storages/storage0/releases/.trash"); <START> Assert.assertFalse("Failed to delete artifact during a force delete operation!", <END> new File(repositoryTrashDir, artifactPath).exists()); Assert.assertFalse("Failed to delete artifact during a force delete operation!", new File(repositoryDir, artifactPath).exists()); }</code><technical_language>static import for methods instead,</technical_language>

Target:
public void testForceDeleteArtifactAllowed() throws Exception { final String artifactPath = "org/carlspring/strongbox/test-artifact-to-trash/1.1/test-artifact-to-trash-1.1.jar"; final File repositoryTrashDir = new File(BASEDIR + "/storages/storage0/releases/.trash"); final File repositoryDir = new File(BASEDIR + "/storages/storage0/releases/.trash"); assertFalse("Failed to delete artifact during a force delete operation!", new File(repositoryTrashDir, artifactPath).exists()); assertFalse("Failed to delete artifact during a force delete operation!", new File(repositoryDir, artifactPath).exists()); }
Source:
<code>public synchronized void storeOrMergeSummary(String queryId, String source, int stageId, int taskId, int driverId, DynamicFilterSummary dynamicFilterSummary, int expectedSummariesCount) { DynamicFilterSummaryWithSenders dynamicFilterSummaryWithSenders = dynamicFilterSummaries.getOrDefault(SourceDescriptor.of(queryId, source), new DynamicFilterSummaryWithSenders()); dynamicFilterSummaryWithSenders.addSummary(stageId, taskId, driverId, dynamicFilterSummary, expectedSummariesCount); <START> dynamicFilterSummaries.put(SourceDescriptor.of(queryId, source), dynamicFilterSummaryWithSenders); <END> }</code><technical_language>Remove this do contains check</technical_language>

Target:
public void storeOrMergeSummary(String queryId, String source, int stageId, int taskId, int driverId, DynamicFilterSummary dynamicFilterSummary, int expectedSummariesCount) { DynamicFilterSummary mergedSummary; synchronized (this) { DynamicFilterSummaryWithSenders dynamicFilterSummaryWithSenders = dynamicFilterSummaries.get(SourceDescriptor.of(queryId, source)); checkState(dynamicFilterSummaryWithSenders != null, "Cannot store summary for not pre-registered task"); mergedSummary = dynamicFilterSummaryWithSenders.addSummary(DynamicFilterSummaryWithSenders.StageTaskKey.of(stageId, taskId), driverId, dynamicFilterSummary, expectedSummariesCount); } if (mergedSummary != null) { futures.get(SourceDescriptor.of(queryId, source)).set(mergedSummary); } }
Source:
<code>public void testSanitizeForHtml() { String unsanitized = "< > \" / ' &" + "<script>alert('injected');</script>"; String expected = "&lt; &gt; &quot; &#x2f; &#39; &amp;" + "&lt;script&gt;alert(&#39;injected&#39;);&lt;&#x2f;script&gt;"; String sanitized = Sanitizer.sanitizeForHtml(unsanitized); String sanitizedTwice = Sanitizer.sanitizeForHtml(sanitized); <START> assertEquals(null, Sanitizer.sanitizeForHtml(null)); <END> assertEquals(expected, sanitized); assertEquals(expected, sanitizedTwice); }</code><technical_language><LINK_0> optionally adhere this naming method if more clear I understand current naming method nice sounding ![screen shot 2016-03-22 9 01 07 pm](<LINK_1></technical_language>

Target:
public void testSanitizeForHtml() { sanitizeHtml_receivesNull_returnsNull(); sanitizeHtml_receivesCodeInjection_returnsSanitized(); sanitizeHtml_receivesSanitized_returnsUnchanged(); }
Source:
<code>public static int complexity(CompilationUnitTree cut) { <START> class CompilationUnitVisitor extends CognitiveComplexityVisitor { <END> private int complexity = 0; @Override public void visitMethodDeclaration(MethodDeclarationTree tree) { sumComplexity(tree); } @Override public void visitFunctionDeclaration(FunctionDeclarationTree tree) { sumComplexity(tree); } @Override public void visitFunctionExpression(FunctionExpressionTree tree) { sumComplexity(tree); } private void sumComplexity(FunctionTree tree) { complexity += complexity(tree).getValue(); } private int complexity() { return complexity + super.complexity.value; } } CompilationUnitVisitor compilationUnitVisitor = new CompilationUnitVisitor(); cut.accept(compilationUnitVisitor); return compilationUnitVisitor.complexity(); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') this a "static" class. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public static int complexity(CompilationUnitTree cut) { class CompilationUnitVisitor extends CognitiveComplexityVisitor { private int functionsComplexity = 0; @Override public void visitMethodDeclaration(MethodDeclarationTree tree) { sumComplexity(tree); } @Override public void visitFunctionDeclaration(FunctionDeclarationTree tree) { sumComplexity(tree); } @Override public void visitFunctionExpression(FunctionExpressionTree tree) { sumComplexity(tree); } private void sumComplexity(FunctionTree tree) { functionsComplexity += complexity(tree).getValue(); } private int complexityWithFunctionsAndRestOfSript() { int scriptComplexity = super.complexity.value; return functionsComplexity + scriptComplexity; } } CompilationUnitVisitor compilationUnitVisitor = new CompilationUnitVisitor(); cut.accept(compilationUnitVisitor); return compilationUnitVisitor.complexityWithFunctionsAndRestOfSript(); }
Source:
<code>protected void pollRecords() { if (isPolled) { return; } try { ps.setFetchSize(getFetchSize()); ResultSet result = ps.executeQuery(); if (result.next()) { do { emitQueue.add(getTuple(result)); } while (result.next()); } <START> isPolled = true; <END> } catch (SQLException ex) { throw new RuntimeException(String.format("Error while running query"), ex); } finally { store.disconnect(); } }</code><technical_language>this want poll records in a window? Is this poll interval is sufficiently long prevent multiple calls pollRecords() a single window? in case, if poll interval is reduced, multiple calls call happen in this case</technical_language>

Target:
protected void pollRecords() { if (isPolled) { return; } try { ps.setFetchSize(getFetchSize()); ResultSet result = ps.executeQuery(); if (result.next()) { do { while (!emitQueue.offer(getTuple(result))) { Thread.sleep(DEFAULT_SLEEP_TIME); } } while (result.next()); } isPolled = true; } catch (SQLException ex) { execute = false; threadException = new AtomicReference<Throwable>(ex); } catch (InterruptedException e) { threadException = new AtomicReference<Throwable>(e); } finally { if (!isPollerPartition) { store.disconnect(); } } }
Source:
<code>private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { numbers.add(Double.parseDouble(matcher.group())); } if (numbers.size() <= 1) { return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); <START> return new LiteralSuggestion("LITERAL1", name, latLonList); <END> }</code><technical_language>@Lambeaux hang this is 1 2. I currently constants, I it, if need distinguish literal types line, 1 2 carry significance context</technical_language>

Target:
private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { numbers.add(Double.parseDouble(matcher.group())); } if (numbers.size() <= 1) { LOGGER.trace("Not enough numbers found to suggest a Lat/Lon"); return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); return new LiteralSuggestion(LITERAL_SUGGESTION_ID, name, latLonList); }
Source:
<code>public static CSPDirective fromValue(String value) { if (Strings.isEmpty(value)) <START> return null; <END> for (int i = 0; i < values().length; i++) { if (value.equals(values()[i].getValue())) return values()[i]; } return null; }</code><technical_language>missing curly braces? (also in some other places)</technical_language>

Target:
public static CSPDirective fromValue(String value) { if (Strings.isEmpty(value)) { return null; } for (int i = 0; i < values().length; i++) { if (value.equals(values()[i].getValue())) { return values()[i]; } } return null; }
Source:
<code>public ResolutionException(String message) { <START> this(message, (List<TaxonomicElement>) null); <END> }</code><technical_language>create ambiguity Collections.emptyList() in avoid null</technical_language>

Target:
public ResolutionException(String message) { super(message); }
Source:
<code>public void testNewQueueFromGroovyScript() throws Exception { final Future<MuleMessage> routedMessage = amqpTestClient.setupFunctionTestComponentForFlow( getFunctionalTestComponent("amqpNewQueueFromGroovyScript")); new MuleClient(muleContext).dispatch("vm://amqpNewQueueFromGroovyScript.in", null, null); final String payload = RandomStringUtils.randomAlphanumeric(20); try { <START> new PollingProber(getTestTimeoutSecs() * 1000, 2000).check(new Probe() { <END> public boolean isSatisfied() { try { new MuleClient(muleContext).dispatch("vm://amqpNewQueueFromGroovyScriptEnqueue.in", payload, null); return routedMessage.get(500, TimeUnit.MILLISECONDS) != null; } catch (Exception e) { throw new RuntimeException(e); } } public String describeFailure() { return "Queue was not created."; } }); }catch (Exception e){ fail(); } MuleMessage muleMessage = routedMessage.get(1,TimeUnit.SECONDS); assertThat(payload, is(muleMessage.getPayloadAsString())); }</code><technical_language>This timeout of test</technical_language>

Target:
public void testNewQueueFromGroovyScript() throws Exception { final Future<MuleMessage> routedMessage = amqpTestClient.setupFunctionTestComponentForFlow( getFunctionalTestComponent("amqpNewQueueFromGroovyScript")); new MuleClient(muleContext).dispatch("vm://amqpNewQueueFromGroovyScript.in", null, null); final String payload = RandomStringUtils.randomAlphanumeric(20); try { new PollingProber(POLLING_PROBER_TIMEOUT, POLLING_PROBER_DELAY).check(new Probe() { public boolean isSatisfied() { try { new MuleClient(muleContext).dispatch("vm://amqpNewQueueFromGroovyScriptEnqueue.in", payload, null); return routedMessage.get(500, MILLISECONDS) != null; } catch (Exception e) { return false; } } public String describeFailure() { return "Queue was not created."; } }); } catch (Exception e) { fail(); } MuleMessage muleMessage = routedMessage.get(1,SECONDS); assertThat(muleMessage.getPayloadAsString(), is(payload)); }
Source:
<code>public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { <START> int n = in.read(buffer); <END> if (n == -1) { break; } hash.update(buffer, 0, n); } return hash.hash(); }</code><technical_language>call this "readBytes" "length"</technical_language>

Target:
public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { int length = in.read(buffer); if (length == -1) { break; } hash.update(buffer, 0, length); } return hash.hash(); }
Source:
<code><START> default Table<String, String, List<String>> findAndIndexSamples() { <END> List<VariantSourceDocument> variantSourceEntities = findAll(); Table<String, String, List<String>> studyFileIdsToPositionSamples = HashBasedTable.create(); for (VariantSourceDocument variantSourceDocument : variantSourceEntities) { final Map<String, Integer> sampleNamesToPosition = variantSourceDocument.getSamplesPosition(); if (sampleNamesToPosition == null) { continue; } String[] samples = new String[sampleNamesToPosition.size()]; for (Map.Entry<String, Integer> entry : sampleNamesToPosition.entrySet()) { samples[entry.getValue()] = entry.getKey(); } String studyId = variantSourceDocument.getStudyId(); String fileId = variantSourceDocument.getFileId(); studyFileIdsToPositionSamples.put(studyId, fileId, Arrays.asList(samples)); } return studyFileIdsToPositionSamples; }</code><technical_language>This called for query variants, samples in studies files. discuss improve this</technical_language>

Target:
default Table<String, String, List<String>> findAndIndexSamples() { List<VariantSourceMongo> variantSourceEntities = findAll(); Table<String, String, List<String>> studyFileIdsToPositionSamples = HashBasedTable.create(); for (VariantSourceMongo variantSourceMongo : variantSourceEntities) { final Map<String, Integer> sampleNamesToPosition = variantSourceMongo.getSamplesPosition(); if (sampleNamesToPosition == null) { continue; } String[] samples = new String[sampleNamesToPosition.size()]; for (Map.Entry<String, Integer> entry : sampleNamesToPosition.entrySet()) { samples[entry.getValue()] = entry.getKey(); } String studyId = variantSourceMongo.getStudyId(); String fileId = variantSourceMongo.getFileId(); studyFileIdsToPositionSamples.put(studyId, fileId, Arrays.asList(samples)); } return studyFileIdsToPositionSamples; }
Source:
<code>public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); <START> handleRefreshCapabilitiesResponse(vds, <END> caps); } catch (Throwable t) { onFailure(t); } }</code><technical_language>is change in this patch in order of execution: Previously, logged failure in case of thrown exception, error triggered handleRefreshCapabilitiesResponse(vds, caps); however, this patch, if another exception finally block, exception logged loose info of origin exception. thrown exception logged</technical_language>

Target:
public void onResponse(Map<String, Object> response) { VDSReturnValue caps = (VDSReturnValue) response.get("result"); handleRefreshCapabilitiesResponse(vds, caps, false); }
Source:
<code>private void updateEventTypeInDB(final EventType eventType, final Long newRetentionTime, final Long oldRetentionTime) throws NakadiException { final NakadiException exception = transactionTemplate.execute(action -> { try { eventTypeRepository.update(eventType); <START> updateTimelinesCleanup(eventType.getName(), newRetentionTime, oldRetentionTime); <END> return null; } catch (final NakadiException e) { return e; } }); if (exception != null) { throw exception; } }</code><technical_language>@v-stepanov is clear event type cache updated? sense switch previous line</technical_language>

Target:
private void updateEventTypeInDB(final EventType eventType, final Long newRetentionTime, final Long oldRetentionTime) throws NakadiException { final NakadiException exception = transactionTemplate.execute(action -> { try { updateTimelinesCleanup(eventType.getName(), newRetentionTime, oldRetentionTime); eventTypeRepository.update(eventType); return null; } catch (final NakadiException e) { return e; } }); if (exception != null) { throw exception; } }
Source:
<code>public synchronized AdHocPlannedStatement planSqlCalcite(SqlTask task, NonDdlBatch batch) { VoltSqlValidator validator = new VoltSqlValidator(m_schemaPlus); SqlNode validatedNode = validator.validate(task.getParsedQuery()); VoltSqlToRelConverter converter = VoltSqlToRelConverter.create(validator, m_schemaPlus); RelRoot root = converter.convertQuery(validatedNode, false, true); root = root.withRel(converter.decorrelate(validatedNode, root.rel)); RelTraitSet logicalTraits = root.rel.getTraitSet().replace(VoltDBLRel.VOLTDB_LOGICAL); RelNode nodeAfterLogical = CalcitePlanner.transform(CalcitePlannerType.VOLCANO, PlannerPhase.LOGICAL, root.rel, logicalTraits); nodeAfterLogical.getCluster().getPlanner().addRelTraitDef(RelDistributions.SINGLETON.getTraitDef()); nodeAfterLogical = VoltDBRelUtil.addTraitRecurcively(nodeAfterLogical, RelDistributions.ANY); RelTraitSet physicalTraits = nodeAfterLogical.getTraitSet().replace(VoltDBPRel.VOLTDB_PHYSICAL); <START> RelNode nodeAfterPhysicalConversion = CalcitePlanner.transform(CalcitePlannerType.VOLCANO, <END> PlannerPhase.PHYSICAL_CONVERSION, nodeAfterLogical, physicalTraits); return null; }</code><technical_language>Is nodeAfterPhysicalConversion typed VoltDBPRel? Is this place call VoltDBPRel#toPlanNode()</technical_language>

Target:
public synchronized AdHocPlannedStatement planSqlCalcite(SqlTask task, NonDdlBatch batch) { VoltSqlValidator validator = new VoltSqlValidator(m_schemaPlus); SqlNode validatedNode = validator.validate(task.getParsedQuery()); VoltSqlToRelConverter converter = VoltSqlToRelConverter.create(validator, m_schemaPlus); RelRoot root = converter.convertQuery(validatedNode, false, true); root = root.withRel(converter.decorrelate(validatedNode, root.rel)); RelTraitSet logicalTraits = root.rel.getTraitSet().replace(VoltDBLRel.VOLTDB_LOGICAL); RelNode nodeAfterLogical = CalcitePlanner.transform(CalcitePlannerType.VOLCANO, PlannerPhase.LOGICAL, root.rel, logicalTraits); nodeAfterLogical.getCluster().getPlanner().addRelTraitDef(RelDistributionTraitDef.INSTANCE); nodeAfterLogical = VoltDBRelUtil.addTraitRecurcively(nodeAfterLogical, RelDistributions.SINGLETON); RelTraitSet physicalTraits = nodeAfterLogical.getTraitSet().replace(VoltDBPRel.VOLTDB_PHYSICAL); RelNode nodeAfterPhysicalConversion = CalcitePlanner.transform(CalcitePlannerType.VOLCANO, PlannerPhase.PHYSICAL_CONVERSION, nodeAfterLogical, physicalTraits); return null; }
Source:
<code>public void onRequestDocumentSave(RequestDocumentSaveEvent event) { final JsArrayString ids = event.getData().getDocumentIds(); final Mutable<Boolean> savedSuccessfully = new Mutable<Boolean>(false); final Timer completedTimer = new Timer() { @Override public void run() { <START> server_.requestDocumentSaveCompleted( <END> savedSuccessfully.get(), new VoidServerRequestCallback()); } }; completedTimer.schedule(5000); final Command onCompleted = new Command() { @Override public void execute() { savedSuccessfully.set(true); completedTimer.schedule(0); } }; if (ids == null) { saveAllUnsaved(onCompleted); } else { SerializedCommandQueue queue = new SerializedCommandQueue(); for (final String id : JsUtil.asIterable(ids)) { queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { EditingTarget target = getEditingTargetForId(id); completedTimer.schedule(5000); if (target instanceof TextEditingTarget) { ((TextEditingTarget) target).save(continuation); } else { continuation.execute(); } } }); } queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { onCompleted.execute(); if (continuation != null) continuation.execute(); } }); } }</code><technical_language>this work source windows? written window wind calling this, is want. If clear wire this ping (the problem is largely solved in existing quit logic)</technical_language>

Target:
public void onRequestDocumentSave(RequestDocumentSaveEvent event) { final JsArrayString ids = event.getDocumentIds(); final Mutable<Boolean> savedSuccessfully = new Mutable<Boolean>(false); final Timer completedTimer = new Timer() { @Override public void run() { if (SourceWindowManager.isMainSourceWindow()) { server_.requestDocumentSaveCompleted( savedSuccessfully.get(), new VoidServerRequestCallback()); } } }; completedTimer.schedule(5000); final Command onCompleted = new Command() { @Override public void execute() { savedSuccessfully.set(true); completedTimer.schedule(0); } }; if (ids == null) { saveUnsavedDocuments(onCompleted); } else { final Set<String> idSet = new HashSet<String>(); for (String id : JsUtil.asIterable(ids)) idSet.add(id); saveUnsavedDocuments(idSet, onCompleted); } }
Source:
<code>public void process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers + " values=" + values); if (values != null) { for (int i = 0; i < values.length; i++) { log.finest(" [value " + i + "] = " + values[i]); } } } if (handler.isUsesHeaders() || handler.isUsesContent()) { if (handler.isUsesHeaders() && (headers == null || headers.isEmpty())) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: uses headers but not supplied"); } return; } if (handler.isUsesContent() && (values == null || values.length == 0)) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: uses content values but not supplied"); } return; } } try { handler.process(trace, node, direction, headers, values); } catch (Throwable t) { ProcessorIssue pi = new ProcessorIssue(); pi.setProcessor(processorDescription); pi.setAction(actionDescription); pi.setSeverity(Severity.Error); pi.setDescription(t.getMessage()); <START> node.getProperties().add(new Property(Constants.PROP_FAULT, pi)); <END> } }</code><technical_language>ProcessorIssue removed</technical_language>

Target:
public void process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers + " values=" + values); if (values != null) { for (int i = 0; i < values.length; i++) { log.finest(" [value " + i + "] = " + values[i]); } } } if (handler.isUsesHeaders() || handler.isUsesContent()) { if (handler.isUsesHeaders() && (headers == null || headers.isEmpty())) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: uses headers but not supplied"); } return; } if (handler.isUsesContent() && (values == null || values.length == 0)) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor/Action[" + handler.getAction() + "]: uses content values but not supplied"); } return; } } try { handler.process(trace, node, direction, headers, values); } catch (Throwable t) { log.severe(processorDescription + ":" + actionDescription, t); } }
Source:
<code>private void processLocalHealthReport() { localCorruptionState = getLocalCorruptionState(localCorruptionReport); <START> if (localCorruptionState.shootTimeLock()) { <END> corruptionHandler.notifyRemoteServersOfCorruption(); } }</code><technical_language>flagged elsewhere, this confusing, I a command,</technical_language>

Target:
private void processLocalHealthReport() { localCorruptionState = getLocalCorruptionState(localCorruptionReport); if (localCorruptionState.shouldRejectRequests()) { corruptionHandler.notifyRemoteServersOfCorruption(); } }
Source:
<code>public List<String> unapply(final String value) { if (this.map instanceof HashBiMap) { return Lists.newArrayList(((HashBiMap<String, String>) this.map).inverse().get(value)); } else { <START> return Lists.newArrayList(Maps.filterKeys(map, new Predicate<String>() <END> { @Override public boolean apply(@Nullable String key) { return map.get(key).equals(Strings.nullToEmpty(value)); } }).keySet()); } }</code><technical_language>(minor) this java 8 lambdas key -> map.get(key).equals(Strings.nullToEmpty(value))</technical_language>

Target:
public List<String> unapply(final String value) { String valueToLookup = Strings.nullToEmpty(value); if (this.reverseMap != null) { String val = this.reverseMap.get(valueToLookup); return (val != null) ? Collections.singletonList(val) : Collections.emptyList(); } else { return Lists.newArrayList(Maps.filterKeys(map, key -> map.get(key).equals(valueToLookup)).keySet()); } }
Source:
<code>public DescriptionBuilder withAdditionalAnnotations(List<Annotation> annotations) { for (Annotation a : annotations) { if (a == null) { throw new NullPointerException("Cannot add a null annotation"); } <START> this.annotations.add(a); <END> } return this; }</code><technical_language>This is fine, personally I addAll(annotations) null checks 1) calls invalid arguments side effects, 2) slightly more efficient</technical_language>

Target:
public DescriptionBuilder withAdditionalAnnotations(List<Annotation> annotations) { if (annotations.contains(null)) { throw new NullPointerException("Cannot add a null annotation"); } this.annotations.addAll(annotations); return this; }
Source:
<code>public static void main(String[] args) throws Exception { Logger.getRootLogger().setLevel(Level.WARN); Opts opts = new Opts(); opts.parseArgs(RestoreZookeeper.class.getName(), args); InputStream in = System.in; if (opts.file != null) { in = new FileInputStream(opts.file); } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("<LINK_1>", false); factory.setFeature("<LINK_3>", false); <START> factory.setFeature("<LINK_2>", false); <END> SAXParser parser = factory.newSAXParser(); parser.parse(in, new Restore(ZooReaderWriter.getInstance(), opts.overwrite)); in.close(); }</code><technical_language>features specific a parser. parser expect users is xerces-j 2.7.1, integrated rt.jar JDK6. So, I do instead of more complicated speculative respect a parser: factory.setFeature("<LINK_0>", true); If user is convoluting environment a parser, I sort of anyway. But, this tool is typically run in security context user... a remote service, a vulnerability out-of-the-box anyway</technical_language>

Target:
public static void main(String[] args) throws Exception { Logger.getRootLogger().setLevel(Level.WARN); Opts opts = new Opts(); opts.parseArgs(RestoreZookeeper.class.getName(), args); InputStream in = System.in; if (opts.file != null) { in = new FileInputStream(opts.file); } SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("<LINK_0>", true); SAXParser parser = factory.newSAXParser(); parser.parse(in, new Restore(ZooReaderWriter.getInstance(), opts.overwrite)); in.close(); }
Source:
<code>private void connectToDatabase() { try { errCnt = 0; logger.debug("mySQL: Attempting to connect to database {}", url); Class.forName(driverClass).newInstance(); connection = DriverManager.getConnection(url, user, password); logger.debug("mySQL: Connected to database {}", url); Statement st = connection.createStatement(); int result = st.executeUpdate("SHOW TABLES LIKE 'Items'"); st.close(); if (waitTimeout != -1) { logger.debug("mySQL: Setting wait_timeout to seconds.", waitTimeout); st = connection.createStatement(); st.executeUpdate("SET SESSION wait_timeout=" + waitTimeout); st.close(); } if (result == 0) { st = connection.createStatement(); st.executeUpdate( "CREATE TABLE Items (ItemId INT NOT NULL AUTO_INCREMENT,ItemName VARCHAR(200) NOT NULL,PRIMARY KEY (ItemId));", Statement.RETURN_GENERATED_KEYS); st.close(); } st = connection.createStatement(); st.setFetchSize(50); ResultSet rs = st.executeQuery("SELECT ItemId, ItemName FROM Items"); while (rs.next()) { sqlTables.put(rs.getString(2), "Item" + rs.getInt(1)); } rs.close(); st.close(); } catch (Exception e) { logger.error( "mySQL: Failed connecting to the SQL database using: driverClass={}, url={}, user={}, password={}", <START> driverClass, url, user, password.replaceAll(".", "*"), e); <END> } }</code><technical_language>Yes, removed other places logging. remove trace statements</technical_language>

Target:
private void connectToDatabase() { try { errCnt = 0; logger.debug("mySQL: Attempting to connect to database {}", url); Class.forName(driverClass).newInstance(); connection = DriverManager.getConnection(url, user, password); logger.debug("mySQL: Connected to database {}", url); Statement st = connection.createStatement(); int result = st.executeUpdate("SHOW TABLES LIKE 'Items'"); st.close(); if (waitTimeout != -1) { logger.debug("mySQL: Setting wait_timeout to seconds.", waitTimeout); st = connection.createStatement(); st.executeUpdate("SET SESSION wait_timeout=" + waitTimeout); st.close(); } if (result == 0) { st = connection.createStatement(); st.executeUpdate( "CREATE TABLE Items (ItemId INT NOT NULL AUTO_INCREMENT,ItemName VARCHAR(200) NOT NULL,PRIMARY KEY (ItemId));", Statement.RETURN_GENERATED_KEYS); st.close(); } st = connection.createStatement(); st.setFetchSize(50); ResultSet rs = st.executeQuery("SELECT ItemId, ItemName FROM Items"); while (rs.next()) { sqlTables.put(rs.getString(2), "Item" + rs.getInt(1)); } rs.close(); st.close(); } catch (Exception e) { logger.error( "mySQL: Failed connecting to the SQL database using: driverClass={}, url={}, user={}", driverClass, url, user, e); } }