auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
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()); ArgumentCaptor<EmailRecordSearchCriteria> captor = ArgumentCaptor.forClass(EmailRecordSearchCriteria.class); verify(auditService).findEmailRecords(captor.capture()); }

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:
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(); } break; case STRING: return value.asText(); default: throw new IllegalStateException("Unexpected value: " + value.getNodeType()); } } return value; }

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:
private boolean showPermissionRequestPromptOnAndroid10IfNeeded(boolean wifiFilterEnabled) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { return false; } final PreferenceScreen prefScreen = getPreferenceScreen(); 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; }

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:
public void assertDoesNotStartWith(AssertionInfo info, CharSequence actual, CharSequence prefix) { if (prefix == null) throw new NullPointerException("The given prefix should not be null"); assertNotNull(info, actual); if (comparisonStrategy.stringStartsWith(actual.toString(), prefix.toString())) throw failures.failure(info, shouldNotStartWith(actual, prefix, comparisonStrategy)); }

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:
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; return base.hasPermission(a,permission); } }; }

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:
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>() { @Nullable @Override public Task apply(DataSegment input) { return new SubTask(groupId, segment, indexSpec, force, validate); } } ); }

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:
public Object visit(ASTMethodOrConstructorDeclaration node, Object data) { int cyclo = (int) Metrics.get(OperationMetricKey.NCSS, node); if (cyclo >= methodReportLevel) { addViolation(data, node, new String[] {node instanceof ASTMethodDeclaration ? "method" : "constructor", node.getQualifiedName().getOperation(), "" + cyclo, }); } return data; }

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:
private static Options createOptions() { Options options = new Options(); Option scriptPath = new Option(null, "scriptPath", true, "path to directory/jar for script(s) lookup"); 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; }

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:
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); } catch (GoogleJsonResponseException gjre) { } bout.reset(); }

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:
public void peopleMessage(final PeopleDescription peopleDescription) { try { peopleDescription.getMessage().toString(); 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); } }

Target:
public void peopleMessage(final PeopleDescription peopleDescription) { final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); }
Source:
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"); Assert.assertFalse("Failed to delete artifact during a force delete operation!", new File(repositoryTrashDir, artifactPath).exists()); Assert.assertFalse("Failed to delete artifact during a force delete operation!", new File(repositoryDir, artifactPath).exists()); }

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:
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); dynamicFilterSummaries.put(SourceDescriptor.of(queryId, source), dynamicFilterSummaryWithSenders); }

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:
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); assertEquals(null, Sanitizer.sanitizeForHtml(null)); assertEquals(expected, sanitized); assertEquals(expected, sanitizedTwice); }

Target:
public void testSanitizeForHtml() { sanitizeHtml_receivesNull_returnsNull(); sanitizeHtml_receivesCodeInjection_returnsSanitized(); sanitizeHtml_receivesSanitized_returnsUnchanged(); }
Source:
public static int complexity(CompilationUnitTree cut) { class CompilationUnitVisitor extends CognitiveComplexityVisitor { 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(); }

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:
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()); } isPolled = true; } catch (SQLException ex) { throw new RuntimeException(String.format("Error while running query"), ex); } finally { store.disconnect(); } }

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:
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(", ")); return new LiteralSuggestion("LITERAL1", name, latLonList); }

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:
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; }

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:
public ResolutionException(String message) { this(message, (List<TaxonomicElement>) null); }

Target:
public ResolutionException(String message) { super(message); }
Source:
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(getTestTimeoutSecs() * 1000, 2000).check(new Probe() { 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())); }

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:
public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { int n = in.read(buffer); if (n == -1) { break; } hash.update(buffer, 0, n); } return hash.hash(); }

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:
default Table<String, String, List<String>> findAndIndexSamples() { 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; }

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:
public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); handleRefreshCapabilitiesResponse(vds, caps); } catch (Throwable t) { onFailure(t); } }

Target:
public void onResponse(Map<String, Object> response) { VDSReturnValue caps = (VDSReturnValue) response.get("result"); handleRefreshCapabilitiesResponse(vds, caps, false); }
Source:
private void updateEventTypeInDB(final EventType eventType, final Long newRetentionTime, final Long oldRetentionTime) throws NakadiException { final NakadiException exception = transactionTemplate.execute(action -> { try { eventTypeRepository.update(eventType); updateTimelinesCleanup(eventType.getName(), newRetentionTime, oldRetentionTime); return null; } catch (final NakadiException e) { return e; } }); if (exception != null) { throw exception; } }

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:
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); RelNode nodeAfterPhysicalConversion = CalcitePlanner.transform(CalcitePlannerType.VOLCANO, PlannerPhase.PHYSICAL_CONVERSION, nodeAfterLogical, physicalTraits); return null; }

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:
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() { 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) { 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(); } }); } }

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:
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()); node.getProperties().add(new Property(Constants.PROP_FAULT, pi)); } }

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:
private void processLocalHealthReport() { localCorruptionState = getLocalCorruptionState(localCorruptionReport); if (localCorruptionState.shootTimeLock()) { corruptionHandler.notifyRemoteServersOfCorruption(); } }

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

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:
public DescriptionBuilder withAdditionalAnnotations(List<Annotation> annotations) { for (Annotation a : annotations) { if (a == null) { throw new NullPointerException("Cannot add a null annotation"); } this.annotations.add(a); } return this; }

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:
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); factory.setFeature("<LINK_2>", false); SAXParser parser = factory.newSAXParser(); parser.parse(in, new Restore(ZooReaderWriter.getInstance(), opts.overwrite)); in.close(); }

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:
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={}", driverClass, url, user, password.replaceAll(".", "*"), e); } }

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); } }
Source:
public final void createIndex(final IndexDesc index) throws DuplicateIndexException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createIndex(null, index.getProto()); throwsIfThisError(state, DuplicateIndexException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }

Target:
public final void createIndex(final IndexDesc index) throws DuplicateIndexException, UndefinedDatabaseException, UndefinedTableException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createIndex(null, index.getProto()); throwsIfThisError(state, DuplicateIndexException.class); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, UndefinedDatabaseException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
private static Predicate<Element> isNotTrusted(TrustedDomains trustedDomains) { return element -> { Optional<URI> maybeRessourceUri = SupportedElements.getHost(element); return element.getAttributeValue("integrity") == null && !maybeRessourceUri .map(ressourceUri -> trustedDomains.isIncluded(ressourceUri.toString())) .orElse(false); }; }

Target:
private static Predicate<Element> isNotTrusted(TrustedDomains trustedDomains) { return element -> { Optional<URI> maybeResourceUri = SupportedElements.getHost(element); return element.getAttributeValue("integrity") == null && !maybeResourceUri .map(resourceUri -> trustedDomains.isIncluded(resourceUri.toString())) .orElse(false); }; }
Source:
public static UserDefinedFunction createFunction( FunctionDescriptor descriptor, ClassLoader classLoader, boolean performValidation, ReadableConfig config) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(descriptor.toProperties()); if (performValidation) { new FunctionDescriptorValidator().validate(properties); } Object instance; switch (properties.getString(FunctionDescriptorValidator.FROM)) { case FunctionDescriptorValidator.FROM_VALUE_CLASS: instance = generateInstance( HierarchyDescriptorValidator.EMPTY_PREFIX, properties, classLoader); break; case FunctionDescriptorValidator.FROM_VALUE_PYTHON: String fullyQualifiedName = properties.getString(PythonFunctionValidator.FULLY_QUALIFIED_NAME); try { Class pythonFunctionFactory = Class.forName( "org.apache.flink.client.python.PythonFunctionFactory", true, Thread.currentThread().getContextClassLoader()); instance = pythonFunctionFactory.getMethod( "getPythonFunction", String.class, ReadableConfig.class) .invoke(null, fullyQualifiedName, config); } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { throw new IllegalStateException( String.format( "Instantiating python function '%s' failed.", fullyQualifiedName), e); } break; default: throw new ValidationException("Unsupported function descriptor: " + properties); } if (!UserDefinedFunction.class.isAssignableFrom(instance.getClass())) { throw new ValidationException(String.format( "Instantiated class '%s' is not a user-defined function.", instance.getClass().getName())); } return (UserDefinedFunction) instance; }

Target:
public static UserDefinedFunction createFunction( FunctionDescriptor descriptor, ClassLoader classLoader, boolean performValidation, ReadableConfig config) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(descriptor.toProperties()); if (performValidation) { new FunctionDescriptorValidator().validate(properties); } Object instance; switch (properties.getString(FunctionDescriptorValidator.FROM)) { case FunctionDescriptorValidator.FROM_VALUE_CLASS: instance = generateInstance( HierarchyDescriptorValidator.EMPTY_PREFIX, properties, classLoader); break; case FunctionDescriptorValidator.FROM_VALUE_PYTHON: String fullyQualifiedName = properties.getString(PythonFunctionValidator.FULLY_QUALIFIED_NAME); instance = PythonFunctionUtils.getPythonFunction(fullyQualifiedName, config); break; default: throw new ValidationException(String.format( "Unsupported function descriptor: %s", properties.getString(FunctionDescriptorValidator.FROM))); } if (!UserDefinedFunction.class.isAssignableFrom(instance.getClass())) { throw new ValidationException(String.format( "Instantiated class '%s' is not a user-defined function.", instance.getClass().getName())); } return (UserDefinedFunction) instance; }
Source:
private List<Plugin> getDefaultPluginConfig() { List<Plugin> plugins = new ArrayList<>(); plugins.add(new Plugin("org.eclipse.core.runtime", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.common", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.ds", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.p2.reconciler.dropins", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.simpleconfigurator", true, 1)); plugins.add(new Plugin("org.eclipse.update.configurator", true, 1)); return plugins; }

Target:
private List<Plugin> getDefaultPluginConfig() { List<Plugin> plugins = new ArrayList<>(); plugins.add(new Plugin("org.eclipse.update.configurator", true, 1)); plugins.add(new Plugin("org.eclipse.equinox.simpleconfigurator", true, 1)); plugins.add(new Plugin("org.eclipse.equinox.ds", true, 2)); plugins.add(new Plugin("org.eclipse.equinox.common", true, 2)); plugins.add(new Plugin("org.eclipse.core.runtime", true, 4)); plugins.add(new Plugin("org.eclipse.equinox.p2.reconciler.dropins", true, 4)); return plugins; }
Source:
private synchronized void loadPatterns() throws DotDataException { patternsCache = new TreeSet<>(); final List<SimpleStructureURLMap> urlMaps = StructureFactory.findStructureURLMapPatterns(); final StringBuilder masterRegEx = new StringBuilder(); for (final SimpleStructureURLMap urlMap : urlMaps) { final PatternCache patternCache = new PatternCache(); final String regEx = StructureUtil.generateRegExForURLMap(urlMap.getURLMapPattern()); if (!UtilMethods.isSet(regEx) || regEx.trim().length() < 3) { continue; } patternCache.setRegEx(regEx); patternCache.setStructureInode(urlMap.getInode()); patternCache.setURLpattern(urlMap.getURLMapPattern()); patternCache.setFieldMatches(getFieldMathed(urlMap)); patternsCache.add(patternCache); if (masterRegEx.length() > 0) { masterRegEx.append('|'); } masterRegEx.append(regEx); } CacheLocator.getContentTypeCache().addURLMasterPattern(masterRegEx.toString()); }

Target:
private synchronized void loadPatterns() throws DotDataException { patternsCache = new TreeSet<>(); final List<SimpleStructureURLMap> urlMaps = StructureFactory.findStructureURLMapPatterns(); final StringBuilder masterRegEx = new StringBuilder(); for (final SimpleStructureURLMap urlMap : urlMaps) { final String regEx = StructureUtil.generateRegExForURLMap(urlMap.getURLMapPattern()); if (!UtilMethods.isSet(regEx) || regEx.trim().length() < 3) { continue; } patternsCache.add(new ContentTypeURLPattern( regEx, urlMap.getInode(), urlMap.getURLMapPattern(), getFieldMathed(urlMap) )); if (masterRegEx.length() > 0) { masterRegEx.append('|'); } masterRegEx.append(regEx); } CacheLocator.getContentTypeCache().addURLMasterPattern(masterRegEx.toString()); }
Source:
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey); cb.setStore(fs); CachingFreenetStore<T> cachingStore = new CachingFreenetStore<T>(cb, cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, fs, ticker); return cachingStore; }

Target:
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey); cb.setStore(fs); return new CachingFreenetStore<T>(cb, cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, fs, ticker); }
Source:
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { if (!isInternalExecution() && getStoragePool() != null && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT) { List<QuotaConsumptionParameter> consumptionParameters = getQuotaConsumptionParameters(); if (consumptionParameters != null) { for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { if (parameter.getQuotaGuid() != null && parameter.getQuotaGuid() != Guid.Empty && parameter.getParameterType() != QuotaConsumptionParameter.ParameterType.SANITY) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } } } }

Target:
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { if (!isInternalExecution() && getStoragePool() != null && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT) { List<QuotaConsumptionParameter> consumptionParameters = getQuotaConsumptionParameters(); if (consumptionParameters != null) { for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { if (parameter.getQuotaGuid() != null && !Guid.Empty.equals(parameter.getQuotaGuid())) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } } } }
Source:
public void comments() throws Exception { PushOneCommit.Result r = createChange(); CommentInput in = new CommentInput(); in.line = 1; in.message = "nit: trailing hitespace"; in.path = FILE_NAME; ReviewInput reviewInput = new ReviewInput(); Map<String, List<CommentInput>> comments = new HashMap<>(); comments.put(FILE_NAME, Collections.singletonList(in)); reviewInput.comments = comments; reviewInput.message = "comment test"; gApi.changes() .id(r.getChangeId()) .current() .review(reviewInput); Map<String, List<CommentInfo>> out = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comments(); assertThat(out).hasSize(1); CommentInfo comment = Iterables.getOnlyElement(out.get(FILE_NAME)); assertThat(comment.message).isEqualTo(in.message); assertThat(comment.author.email).isEqualTo(admin.email); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comment(comment.id) .get() .message) .isEqualTo(in.message); }

Target:
public void comments() throws Exception { PushOneCommit.Result r = createChange(); CommentInput in = new CommentInput(); in.line = 1; in.message = "nit: trailing whitespace"; in.path = FILE_NAME; ReviewInput reviewInput = new ReviewInput(); Map<String, List<CommentInput>> comments = new HashMap<>(); comments.put(FILE_NAME, Collections.singletonList(in)); reviewInput.comments = comments; reviewInput.message = "comment test"; gApi.changes() .id(r.getChangeId()) .current() .review(reviewInput); Map<String, List<CommentInfo>> out = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comments(); assertThat(out).hasSize(1); CommentInfo comment = Iterables.getOnlyElement(out.get(FILE_NAME)); assertThat(comment.message).isEqualTo(in.message); assertThat(comment.author.email).isEqualTo(admin.email); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .comment(comment.id) .get() .message) .isEqualTo(in.message); }