auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Void call() throws Exception { Objects.requireNonNull(version, "Version hasn't been set."); updateTitle(i18n.get("game.mapGeneration.generateMap.title", version, String.valueOf(seed))); Path workingDirectory = preferencesService.getPreferences().getForgedAlliance().getCustomMapsDirectory(); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(workingDirectory.toFile()); processBuilder.command("java", "-jar", generatorExecutableFile.toAbsolutePath().toString(), ".", String.valueOf(seed), version, mapFilename); processBuilder.environment().put("LOG_DIR", preferencesService.getFafLogDirectory().toAbsolutePath().toString()); log.info("Starting map generator in directory: with command: {}", processBuilder.directory(), processBuilder.command().stream().reduce((l, r) -> l + " " + r).get()); try { Process process = processBuilder.start(); OsUtils.gobbleLines(process.getInputStream(), logger::info); OsUtils.gobbleLines(process.getErrorStream(), logger::error); process.waitFor(MapGeneratorService.GENERATION_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (process.isAlive()) { log.warn("Map generation timed out, killing process..."); process.destroyForcibly(); notificationService.addNotification(new ImmediateNotification(i18n.get("game.mapGeneration.failed.title"), i18n.get("game.mapGeneration.failed.message"), Severity.ERROR)); } else { eventBus.post(new MapGeneratedEvent(mapFilename)); } } catch (IOException | InterruptedException e) { log.error("Could not start map generator.", e); throw new RuntimeException(e); } return null; }

Target:
protected Void call() throws Exception { Objects.requireNonNull(version, "Version hasn't been set."); updateTitle(i18n.get("game.mapGeneration.generateMap.title", version, String.valueOf(seed))); Path workingDirectory = preferencesService.getPreferences().getForgedAlliance().getCustomMapsDirectory(); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(workingDirectory.toFile()); processBuilder.command("java", "-jar", generatorExecutableFile.toAbsolutePath().toString(), ".", String.valueOf(seed), version, mapFilename); processBuilder.environment().put("LOG_DIR", preferencesService.getFafLogDirectory().toAbsolutePath().toString()); log.info("Starting map generator in directory: with command: {}", processBuilder.directory(), processBuilder.command().stream().reduce((l, r) -> l + " " + r).get()); try { Process process = processBuilder.start(); OsUtils.gobbleLines(process.getInputStream(), generatorLogger::info); OsUtils.gobbleLines(process.getErrorStream(), generatorLogger::error); process.waitFor(MapGeneratorService.GENERATION_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (process.isAlive()) { log.warn("Map generation timed out, killing process..."); process.destroyForcibly(); notificationService.addNotification(new ImmediateNotification(i18n.get("game.mapGeneration.failed.title"), i18n.get("game.mapGeneration.failed.message"), Severity.ERROR)); } else { eventBus.post(new MapGeneratedEvent(mapFilename)); } } catch (IOException | InterruptedException e) { log.error("Could not start map generator.", e); throw new RuntimeException(e); } return null; }
Source:
public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String mimeType = (String) in.getHeader("MimeType"); final ExecResult result = (ExecResult) in.getBody(); String derivativePath = new BufferedReader(new InputStreamReader(result.getStdout())) .lines().collect(Collectors.joining("\n")); InputStream binaryStream = new FileInputStream(derivativePath + ".PNG"); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, derivativePath, mimeType, PcdmUse.ThumbnailImage); log.info("Adding derivative for from {}", binaryUri, derivativePath); }

Target:
public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryMimeType = (String) in.getHeader(CdrBinaryMimeType); final ExecResult result = (ExecResult) in.getBody(); String derivativePath = new BufferedReader(new InputStreamReader(result.getStdout())) .lines().collect(Collectors.joining("\n")); InputStream binaryStream = new FileInputStream(derivativePath + "." + fileExtension); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, derivativePath, binaryMimeType, PcdmUse.ThumbnailImage); log.info("Adding derivative for from {}", binaryUri, derivativePath); }
Source:
private void startFormEntry(AndroidSessionWrapper state) throws SessionUnavailableException { if (state.getFormRecordId() == -1) { if (CommCarePreferences.isIncompleteFormsEnabled() && state.getSessionStateDescriptor().getSessionDescriptor().contains(SessionFrame.STATE_DATUM_VAL)) { SessionStateDescriptor existing = state.searchForDuplicates(); if (existing != null) { createAskUseOldDialog(state, existing); return; } } state.commitStub(); } else { Logger.log("form-entry", "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); if (platform == null && CommCareApplication._().getCurrentApp() != null) { platform = CommCareApplication._().getCommCarePlatform(); } formEntry(platform.getFormContentUri(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null)); }

Target:
private void startFormEntry(AndroidSessionWrapper state) throws SessionUnavailableException { if (state.getFormRecordId() == -1) { if (CommCarePreferences.isIncompleteFormsEnabled()) { SessionStateDescriptor existing = state.getExistingIncompleteCaseDescriptor(); if (existing != null) { createAskUseOldDialog(state, existing); return; } } state.commitStub(); } else { Logger.log("form-entry", "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); if (platform == null && CommCareApplication._().getCurrentApp() != null) { platform = CommCareApplication._().getCommCarePlatform(); } formEntry(platform.getFormContentUri(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null)); }
Source:
public void fail_to_update_custom_rule_when_empty_name() { RuleDefinitionDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).getDefinition(); db.rules().insert(templateRule); RuleDefinitionDto customRule = RuleTesting.newCustomRule(templateRule); db.rules().insert(customRule); dbSession.commit(); RuleUpdate update = RuleUpdate.createForCustomRule(customRule.getKey()) .setName("") .setMarkdownDescription("New desc") .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("The name is missing"); underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }

Target:
public void fail_to_update_custom_rule_when_empty_name() { RuleDefinitionDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).getDefinition(); db.rules().insert(templateRule); RuleDefinitionDto customRule = RuleTesting.newCustomRule(templateRule); db.rules().insert(customRule); dbSession.commit(); RuleUpdate update = createForCustomRule(customRule.getKey()) .setName("") .setMarkdownDescription("New desc") .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("The name is missing"); underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }
Source:
public Integer resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } int cpu = ((CtfTmfEvent) event).getCPU(); if (cpu == -1) { ITmfEventField content = event.getContent(); Long fieldValue = null; if (content != null) { fieldValue = content.getFieldValue(Long.class, CPU_ID); } return fieldValue == null ? null : fieldValue.intValue(); } return cpu; }

Target:
public Integer resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } int cpu = ((CtfTmfEvent) event).getCPU(); if (cpu == IEventDefinition.UNKNOWN_CPU) { ITmfEventField content = event.getContent(); Long fieldValue = null; if (content != null) { fieldValue = content.getFieldValue(Long.class, CPU_ID); } return fieldValue == null ? null : fieldValue.intValue(); } return cpu; }
Source:
private static int[] orderStreamReaders(Collection<Integer> columnIndices, Map<Integer, Integer> columnToScore, Set<Integer> filterFunctionInputs) { List<Integer> sortedColumnsByFilterScore = columnToScore.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .map(entry -> entry.getKey()) .collect(Collectors.toList()); int[] order = new int[columnIndices.size()]; int i = 0; for (int columnIndex : sortedColumnsByFilterScore) { if (columnIndices.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : filterFunctionInputs) { if (columnIndices.contains(columnIndex) && !sortedColumnsByFilterScore.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : columnIndices) { if (!sortedColumnsByFilterScore.contains(columnIndex) && !filterFunctionInputs.contains(columnIndex)) { order[i++] = columnIndex; } } return order; }

Target:
private static int[] orderStreamReaders(Collection<Integer> columnIndices, Map<Integer, Integer> columnToScore, Set<Integer> filterFunctionInputs) { List<Integer> sortedColumnsByFilterScore = columnToScore.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .collect(toImmutableList()); int[] order = new int[columnIndices.size()]; int i = 0; for (int columnIndex : sortedColumnsByFilterScore) { if (columnIndices.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : filterFunctionInputs) { if (columnIndices.contains(columnIndex) && !sortedColumnsByFilterScore.contains(columnIndex)) { order[i++] = columnIndex; } } for (int columnIndex : columnIndices) { if (!sortedColumnsByFilterScore.contains(columnIndex) && !filterFunctionInputs.contains(columnIndex)) { order[i++] = columnIndex; } } return order; }
Source:
private OptionHandler findHandler(String name) { if (options == null) { options = Maps.newHashMap(); for (OptionHandler handler : parser.options) { if (handler.option instanceof NamedOptionDef) { NamedOptionDef def = (NamedOptionDef) handler.option; if (!def.isArgument()) { options.put(def.name(), handler); for (String alias : def.aliases()) { options.put(alias, handler); } } } } return options.get(name); } return options.get(name); }

Target:
private OptionHandler findHandler(String name) { if (options == null) { options = index(parser.options); } return options.get(name); }
Source:
protected Result pushDownDereferences(Context context, N targetNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = getOnlyElement(targetNode.getSources()); ImmutableMap<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream().collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); ProjectNode projectNode = new ProjectNode( context.getIdAllocator().getNextId(), source, Assignments.builder().putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())).putAll(dereferencesMap).build()); return Result.ofPlanNode(targetNode.replaceChildren(ImmutableList.of(projectNode))); }

Target:
protected Result pushDownDereferences(Context context, N targetNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { PlanNode source = getOnlyElement(targetNode.getSources()); Map<VariableReferenceExpression, RowExpression> dereferencesMap = expressions.inverse().entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> castToRowExpression(entry.getValue()))); ProjectNode projectNode = new ProjectNode( context.getIdAllocator().getNextId(), source, Assignments.builder() .putAll(identityAssignmentsAsSymbolReferences(source.getOutputVariables())) .putAll(dereferencesMap) .build()); return Result.ofPlanNode(targetNode.replaceChildren(ImmutableList.of(projectNode))); }
Source:
private void initReadCategory(final ReviewDb c, final SystemConfig sConfig) throws OrmException { final Transaction txn = c.beginTransaction(); final ApprovalCategory cat; final ArrayList<ApprovalCategoryValue> vals; cat = new ApprovalCategory(ApprovalCategory.READ, "Read Access"); cat.setPosition((short) -1); cat.setFunctionName(NoOpFunction.NAME); vals = new ArrayList<ApprovalCategoryValue>(); vals.add(value(cat, 2, "Upload permission")); vals.add(value(cat, 1, "Read access")); vals.add(value(cat, -1, "No access")); c.approvalCategories().insert(Collections.singleton(cat), txn); c.approvalCategoryValues().insert(vals, txn); txn.commit(); { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.anonymousGroupId)); read.setMaxValue((short) 1); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.adminGroupId)); read.setMaxValue((short) 1); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } }

Target:
private void initReadCategory(final ReviewDb c, final SystemConfig sConfig) throws OrmException { final Transaction txn = c.beginTransaction(); final ApprovalCategory cat; final ArrayList<ApprovalCategoryValue> vals; cat = new ApprovalCategory(ApprovalCategory.READ, "Read Access"); cat.setPosition((short) -1); cat.setFunctionName(NoOpFunction.NAME); vals = new ArrayList<ApprovalCategoryValue>(); vals.add(value(cat, 2, "Upload permission")); vals.add(value(cat, 1, "Read access")); vals.add(value(cat, -1, "No access")); c.approvalCategories().insert(Collections.singleton(cat), txn); c.approvalCategoryValues().insert(vals, txn); txn.commit(); { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.anonymousGroupId)); read.setMaxValue((short) 2); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } { final ProjectRight read = new ProjectRight(new ProjectRight.Key(DEFAULT_WILD_NAME, cat.getId(), sConfig.adminGroupId)); read.setMaxValue((short) 1); read.setMinValue((short) 1); c.projectRights().insert(Collections.singleton(read)); } }
Source:
public final boolean evaluate(Object feature) { final Object object1 = eval(expression1, feature); final Object object2 = eval(expression2, feature); Collection<Object> collection1 = getCollection(object1); Collection<Object> collection2 = getCollection(object2); if (collection1 == null && collection2 == null) { return evaluateInternal(object1, object2); } Collection<Object> leftValues = collection1 instanceof Collection ? collection1 : Collections.<Object>singletonList(object1); Collection<Object> rightValues = collection2 instanceof Collection ? collection2 : Collections.<Object>singletonList(object2); int count = 0; for (Object value1 : leftValues) { for (Object value2 : rightValues) { boolean temp = evaluateInternal(value1, value2); if (temp) { count++; } switch (matchAction) { case ONE: if (count > 1) return false; break; case ALL: if (!temp) return false; break; case ANY: if (temp) return true; break; } } } switch (matchAction) { case ONE: return (count == 1); case ALL: return true; case ANY: return false; default: return false; } }

Target:
public final boolean evaluate(Object feature) { final Object object1 = eval(expression1, feature); final Object object2 = eval(expression2, feature); Collection<Object> collection1 = toCollection(object1); Collection<Object> collection2 = toCollection(object2); if (collection1 == null && collection2 == null) { return evaluateInternal(object1, object2); } Collection<Object> leftValues = collection1 instanceof Collection ? collection1 : Collections.<Object>singletonList(object1); Collection<Object> rightValues = collection2 instanceof Collection ? collection2 : Collections.<Object>singletonList(object2); int count = 0; for (Object value1 : leftValues) { for (Object value2 : rightValues) { boolean temp = evaluateInternal(value1, value2); if (temp) { count++; } switch (matchAction) { case ONE: if (count > 1) return false; break; case ALL: if (!temp) return false; break; case ANY: if (temp) return true; break; } } } switch (matchAction) { case ONE: return (count == 1); case ALL: return true; case ANY: return false; default: return false; } }
Source:
private void loadProperties() { if (file != null && file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); if (logger.isInfoEnabled()) { logger.info( String.format( "Load registry store file %s, data: %s", file, properties ) ); } } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (Throwable e) { logger.warn(String.format("Failed to load registry store file %s", file), e); } } }

Target:
private void loadProperties() { if (file != null && file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); if (logger.isInfoEnabled()) { logger.info("Load registry store file: " + file + ", data: " + properties); } } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (Throwable e) { logger.warn(String.format("Failed to load registry store file %s", file), e); } } }
Source:
public StandaloneJsPluginModule(String pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }

Target:
StandaloneJsPluginModule(String pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }
Source:
protected void verifyRelNode(String expectedRelNodeStr, RelNode relNode) { String relNodeStr = RelOptUtil.toString(relNode); System.out.println(relNodeStr); relNodeStr = relNodeStr.replaceAll("\\s", ""); assertEquals(expectedRelNodeStr, relNodeStr); }

Target:
protected void verifyRelNode(String expectedRelNodeStr, RelNode relNode) { String relNodeStr = RelOptUtil.toString(relNode); assertEquals(expectedRelNodeStr, relNodeStr); }
Source:
private List<Serializable> getSerializableParamsOrFail(String nodeSourceName, Object[] params) { List<Serializable> serializableParams = null; if (params != null) { Object currentParam = null; try { serializableParams = new ArrayList<>(params.length); for (int i = 0; i < params.length; i++) { currentParam = params[i]; serializableParams.add(i, (Serializable) currentParam); } } catch (ClassCastException e) { throw new IllegalArgumentException("Parameter " + currentParam + " of defined node source " + nodeSourceName + " is not Serializable"); } } return serializableParams; }

Target:
private List<Serializable> getSerializableParamsOrFail(String nodeSourceName, Object[] params) { List<Serializable> serializableParams = null; if (params != null) { Object currentParam = null; try { serializableParams = new ArrayList<>(params.length); for (int i = 0; i < params.length; i++) { currentParam = params[i]; serializableParams.add(i, (Serializable) currentParam); } } catch (ClassCastException e) { throw new IllegalArgumentException("Parameter " + currentParam + " of defined node source " + nodeSourceName + " is not Serializable", e); } } return serializableParams; }
Source:
private String createActivatedEmailText(User user, String appName) { String firstName = user.getFirstName(); String lastName = user.getLastName(); if (firstName == null || firstName.isEmpty()) firstName = user.getUsername(); if (lastName == null || lastName.isEmpty()) lastName = null; StringBuilder builder = new StringBuilder(); builder.append("Dear "); builder.append(firstName); if (lastName != null) { builder.append(" "); builder.append(lastName); } builder.append(",\n\n"); builder.append("Your registration request for "); builder.append(appName); builder.append(" was approved.\n"); builder.append("Your account is now active.\n\n"); builder.append("Kind regards,\n\n"); builder.append("MOLGENIS support"); return builder.toString(); }

Target:
private String createActivatedEmailText(User user, String appName) { String firstName = user.getFirstName(); String lastName = user.getLastName(); if (firstName == null || firstName.isEmpty()) firstName = user.getUsername(); if (lastName == null || lastName.isEmpty()) lastName = null; StringBuilder builder = new StringBuilder(); builder.append("Dear "); builder.append(firstName); if (lastName != null) { builder.append(" "); builder.append(lastName); } builder.append(",\n\n"); builder.append("Your registration request for "); builder.append(appName); builder.append(" was approved.\n"); builder.append("Your account is now active.\n\n"); builder.append("Kind regards,\n\n"); builder.append("Server administrator"); return builder.toString(); }
Source:
public void cleanserTest() { List<TextAnnotation> toyAnnotations = new ArrayList<>(); for (int i = 0; i < 3 ; i++) { TextAnnotation ta = ToyTextAnnotationGenerator.generateToyTextAnnotation(3); toyAnnotations.add(ta); } Set<String> uncleansed = toyAnnotations.get(0).getAvailableViews(); Set<String> uncleansedViews = new HashSet<>(); uncleansedViews.addAll(uncleansed); List<TextAnnotation> cleansedAnnotations; TokenLabelCleanser cleanser = new TokenLabelCleanser(); cleansedAnnotations = cleanser.removeAnnotations(toyAnnotations); for (TextAnnotation cleansedAnnotation : cleansedAnnotations) { Set<String> views = cleansedAnnotation.getAvailableViews(); Assert.assertEquals(1, views.size()); Assert.assertEquals(2, uncleansedViews.size()); Assert.assertTrue(uncleansedViews.contains(ViewNames.TOKENS)); Assert.assertFalse(views.contains(ViewNames.TOKENS)); } }

Target:
public void cleanserTest() { List<TextAnnotation> toyAnnotations = new ArrayList<>(); for (int i = 0; i < 3 ; i++) { TextAnnotation ta = DummyTextAnnotationGenerator.generateBasicTextAnnotation(1); toyAnnotations.add(ta); } Set<String> uncleansed = toyAnnotations.get(0).getAvailableViews(); Set<String> uncleansedViews = new HashSet<>(); uncleansedViews.addAll(uncleansed); List<TextAnnotation> cleansedAnnotations; TokenLabelCleanser cleanser = new TokenLabelCleanser(); cleansedAnnotations = cleanser.removeAnnotations(toyAnnotations); for (TextAnnotation cleansedAnnotation : cleansedAnnotations) { Set<String> views = cleansedAnnotation.getAvailableViews(); Assert.assertEquals(1, views.size()); Assert.assertEquals(2, uncleansedViews.size()); Assert.assertTrue(uncleansedViews.contains(ViewNames.TOKENS)); Assert.assertFalse(views.contains(ViewNames.TOKENS)); } }
Source:
public List<String> toJSONStrings() { ArrayList<String> list = new ArrayList<>(); for ( RowMap map : jsonMaps() ) { ByteArrayOutputStream b = new ByteArrayOutputStream(); JsonGenerator g = createJSONGenerator(b); try { rowMapToJSON(g, map); g.flush(); list.add(b.toString()); } catch ( IOException e ) { } } return list; }

Target:
public List<String> toJSONStrings() { ArrayList<String> list = new ArrayList<>(); ByteArrayOutputStream b = new ByteArrayOutputStream(); JsonGenerator g = createJSONGenerator(b); g.setRootValueSeparator(null); for ( RowMap map : jsonMaps() ) { try { rowMapToJSON(g, map); b.reset(); g.flush(); list.add(b.toString()); } catch ( IOException e ) { LOGGER.error("Caught IOException while generating JSON: " + e, e); } } return list; }
Source:
protected void executeCommand() { Job job = ExecutionHandler.createJob(VdcActionType.AddExternalJob, this); job.setDescription(getParameters().getDescription()); job.setAutoCleared(getParameters().isAutoCleared()); Guid id = job.getId(); job.setExternal(true); JobRepositoryFactory.getJobRepository().saveJob(job); if (DbFacade.getInstance().getJobDao().get(id) != null) { setActionReturnValue(id); setSucceeded(true); } else { setSucceeded(false); } }

Target:
protected void executeCommand() { Job job = ExecutionHandler.createJob(VdcActionType.AddExternalJob, this); job.setDescription(getParameters().getDescription()); job.setAutoCleared(getParameters().isAutoCleared()); Guid id = job.getId(); job.setExternal(true); JobRepositoryFactory.getJobRepository().saveJob(job); if (getJobDao().get(id) != null) { setActionReturnValue(id); setSucceeded(true); } else { setSucceeded(false); } }
Source:
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(AuthServer.class); }

Target:
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { application.application().setDefaultProperties(DEFAULT_PROPERTIES); return application.sources(AuthServer.class); }
Source:
public String toString() { return new String('[' + String.valueOf(fStart) + ", " + (String.valueOf(fStart + fDuration)) + ']'); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(fStart); sb.append(", "); sb.append(fStart + fDuration); sb.append("]"); return sb.toString(); }
Source:
public static void insertBenchmarkSuite(Handle handle, String suite, String querySet, String phases, String sessionProperties) { handle.execute( "INSERT INTO benchmark_suites(\n" + " suite, query_set, phases, session_properties, created_by, create_time, update_time)\n" + "SELECT\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " 'benchmark',\n" + " CURRENT_TIMESTAMP,\n" + " CURRENT_TIMESTAMP\n", suite, querySet, phases, sessionProperties); }

Target:
public static void insertBenchmarkSuite(Handle handle, String suite, String querySet, String phases, String sessionProperties) { handle.execute( "INSERT INTO benchmark_suites(\n" + " `suite`, `query_set`, `phases`, `session_properties`, `created_by`)\n" + "SELECT\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " 'benchmark'\n", suite, querySet, phases, sessionProperties); }
Source:
public ContentAssistant openContentAssistant(String assistantLabel) { activate(); log.info("Open editor's " + assistantLabel + " content assistant"); AbstractWait.sleep(TimePeriod.SHORT); Shell[] shells1 = ShellLookup.getInstance().getShells(); new ShellMenu("Edit", "Content Assist", assistantLabel).select(); ContentAssistantShellIsOpened caw = new ContentAssistantShellIsOpened( shells1); new WaitUntil(caw); return new ContentAssistant(caw.getContentAssistTable()); }

Target:
public ContentAssistant openContentAssistant(String assistantLabel) { return openContentAssistant("Edit", "Content Assist", assistantLabel); }
Source:
public void getPublicIPAddress() { final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName); boolean jobDone = Predicates2.retry(new Predicate<String>() { @Override public boolean apply(String name) { return ipApi.get(name).properties().provisioningState().equals("Succeeded"); } }, 10 * 1000).apply(publicIpAddressName); assertTrue(jobDone, "getVault operation did not complete in the configured timeout"); PublicIPAddress ip = ipApi.get(publicIpAddressName); assertNotNull(ip); assertEquals(ip.name(), publicIpAddressName); assertEquals(ip.location(), LOCATION); assertEquals(ip.id(), String.format("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", subscriptionid, resourceGroupName, publicIpAddressName)); assertEquals(ip.tags().get("testkey"), "testvalue"); assertNotNull(ip.properties()); assertEquals(ip.properties().provisioningState(), "Succeeded"); assertNotNull(ip.properties().ipAddress()); assertEquals(ip.properties().publicIPAllocationMethod(), "Static"); assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4); }

Target:
public void getPublicIPAddress() { final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName); boolean jobDone = Predicates2.retry(new Predicate<String>() { @Override public boolean apply(String name) { return ipApi.get(name).properties().provisioningState().equals("Succeeded"); } }, 10 * 1000).apply(publicIpAddressName); assertTrue(jobDone, "get operation did not complete in the configured timeout"); PublicIPAddress ip = ipApi.get(publicIpAddressName); assertNotNull(ip); assertEquals(ip.name(), publicIpAddressName); assertEquals(ip.location(), LOCATION); assertEquals(ip.id(), String.format("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", subscriptionid, resourceGroupName, publicIpAddressName)); assertEquals(ip.tags().get("testkey"), "testvalue"); assertNotNull(ip.properties()); assertEquals(ip.properties().provisioningState(), "Succeeded"); assertNotNull(ip.properties().ipAddress()); assertEquals(ip.properties().publicIPAllocationMethod(), "Static"); assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4); }
Source:
public <T> T construct(Class<T> componentType) { if (PendingLockManager.class.equals(componentType)) { final boolean clustered = configuration.clustering().cacheMode().isClustered(); return clustered ? (T) new DefaultPendingLockManager() : (T) NoOpPendingLockManager.getInstance(); } if (configuration.deadlockDetection().enabled()) { return (T) new DeadlockDetectingLockManager(); } else { return (T) new LockManagerImpl(); } }

Target:
public <T> T construct(Class<T> componentType) { if (PendingLockManager.class.equals(componentType)) { return componentType.cast(configuration.clustering().cacheMode().isClustered() ? new DefaultPendingLockManager() : NoOpPendingLockManager.getInstance()); } else if (LockManager.class.equals(componentType)) { return componentType.cast(configuration.deadlockDetection().enabled() ? new DeadlockDetectingLockManager() : new LockManagerImpl()); } throw new IllegalArgumentException("Unexpected component type " + componentType + "."); }
Source:
protected void errorOccurred(ErrorContext context) { if (operationFailedHandler == null) { throw new IllegalStateException("Uninitialised error handler"); } Throwable throwable = context.getThrowable(); if (throwable instanceof LockObtainFailedException) { List<LuceneWork> failingOperations = context.getFailingOperations(); LuceneWork operationAtFault = context.getOperationAtFault(); List<LuceneWork> failed = new ArrayList<>(failingOperations); failed.add(operationAtFault); operationFailedHandler.lockObtainFailed(failed); } }

Target:
protected void errorOccurred(ErrorContext context) { if (operationFailedHandler != null) { Throwable throwable = context.getThrowable(); if (throwable instanceof LockObtainFailedException) { List<LuceneWork> failingOperations = context.getFailingOperations(); LuceneWork operationAtFault = context.getOperationAtFault(); List<LuceneWork> failed = new ArrayList<>(failingOperations); failed.add(operationAtFault); operationFailedHandler.lockObtainFailed(failed); } } }
Source:
public void setDest(final RandomAccessOutputStream stream, final int imageIndex, final SCIFIOConfig config) throws FormatException, IOException { super.setDest(stream, imageIndex, config); if (getStream().length() == 0) { writeHeader(); } }

Target:
public void setDest(final RandomAccessOutputStream stream, final int imageIndex, final SCIFIOConfig config) throws FormatException, IOException { super.setDest(stream, imageIndex, config); if (getStream().length() == 0) writeHeader(); }
Source:
public Pair<String, Boolean> reprocess(OMMetadataManager omMetadataManager) { LOG.info("Starting a 'reprocess' run of FileSizeCountTask."); Table<String, OmKeyInfo> omKeyInfoTable = omMetadataManager.getKeyTable(); try (TableIterator<String, ? extends Table.KeyValue<String, OmKeyInfo>> keyIter = omKeyInfoTable.iterator()) { while(keyIter.hasNext()) { Table.KeyValue<String, OmKeyInfo> kv = keyIter.next(); countFileSize(kv.getValue()); } populateFileCountBySizeDB(); } catch (IOException ioEx) { LOG.error("Unable to populate Container Key Prefix data in Recon DB. ", ioEx); return new ImmutablePair<>(getTaskName(), false); } LOG.info("Completed a 'reprocess' run of FileSizeCountTask."); return new ImmutablePair<>(getTaskName(), true); }

Target:
public Pair<String, Boolean> reprocess(OMMetadataManager omMetadataManager) { LOG.info("Starting a 'reprocess' run of FileSizeCountTask."); Table<String, OmKeyInfo> omKeyInfoTable = omMetadataManager.getKeyTable(); try (TableIterator<String, ? extends Table.KeyValue<String, OmKeyInfo>> keyIter = omKeyInfoTable.iterator()) { while (keyIter.hasNext()) { Table.KeyValue<String, OmKeyInfo> kv = keyIter.next(); updateUpperBoundCount(kv.getValue(), PUT); } } catch (IOException ioEx) { LOG.error("Unable to populate File Size Count in Recon DB. ", ioEx); return new ImmutablePair<>(getTaskName(), false); } populateFileCountBySizeDB(); LOG.info("Completed a 'reprocess' run of FileSizeCountTask."); return new ImmutablePair<>(getTaskName(), true); }
Source:
protected boolean compareAndPut(Ref oldRef, Ref newRef) throws IOException { boolean ret = compareAndPutImpl(oldRef, newRef); if (ret) { objdb.markDirty(); } return ret; }

Target:
protected boolean compareAndPut(Ref oldRef, Ref newRef) throws IOException { try { lock.writeLock().lock(); ObjectId id = newRef.getObjectId(); if (id != null) { try (RevWalk rw = new RevWalk(getRepository())) { rw.parseAny(id); } } String name = newRef.getName(); if (oldRef == null) return refs.putIfAbsent(name, newRef) == null; Ref cur = refs.get(name); Ref toCompare = cur; if (toCompare != null) { if (toCompare.isSymbolic()) { Ref leaf = toCompare.getLeaf(); if (leaf.getObjectId() == null) { leaf = refs.get(leaf.getName()); if (leaf.isSymbolic()) throw new IllegalArgumentException(); toCompare = new SymbolicRef( name, new ObjectIdRef.Unpeeled( Storage.NEW, leaf.getName(), leaf.getObjectId())); } else toCompare = toCompare.getLeaf(); } if (eq(toCompare, oldRef)) return refs.replace(name, cur, newRef); } if (oldRef.getStorage() == Storage.NEW) return refs.putIfAbsent(name, newRef) == null; return false; } finally { lock.writeLock().unlock(); } }
Source:
public void be_able_to_remove_bounded_context_from_builder() { final BoundedContext firstBoundedContext = newBoundedContext("Removed"); final BoundedContext secondBoundedContext = newBoundedContext("Also removed"); final BoundedContext thirdBoundedContext = newBoundedContext("The one to stay"); final SubscriptionService subscriptionService = SubscriptionService.newBuilder() .addBoundedContext(firstBoundedContext) .addBoundedContext(secondBoundedContext) .addBoundedContext(thirdBoundedContext) .removeBoundedContext(secondBoundedContext) .removeBoundedContext(firstBoundedContext) .build(); assertNotNull(subscriptionService); }

Target:
public void be_able_to_remove_bounded_context_from_builder() { final BoundedContext firstBoundedContext = newBoundedContext("Removed", newSimpleStand()); final BoundedContext secondBoundedContext = newBoundedContext("Also removed", newSimpleStand()); final BoundedContext thirdBoundedContext = newBoundedContext("The one to stay", newSimpleStand()); final SubscriptionService.Builder builder = SubscriptionService.newBuilder() .addBoundedContext(firstBoundedContext) .addBoundedContext(secondBoundedContext) .addBoundedContext(thirdBoundedContext) .removeBoundedContext(secondBoundedContext) .removeBoundedContext(firstBoundedContext); final SubscriptionService subscriptionService = builder.build(); assertNotNull(subscriptionService); final List<BoundedContext> boundedContexts = builder.getBoundedContexts(); assertSize(1, boundedContexts); assertFalse(boundedContexts.contains(firstBoundedContext)); assertFalse(boundedContexts.contains(secondBoundedContext)); assertTrue(boundedContexts.contains(thirdBoundedContext)); }
Source:
private void handleSetDetails(Message message) { if (isCorrectEvent(message, CommActions.ACTIONDETAILS)) { handleCommEventSync(message, CommActions.ACTIONDETAILS, this::onActionDetails); } LOGGER.warn("Warning: set details handler received non-set details message " + message.toString()); }

Target:
private void handleSetDetails(Message message) { if (isCorrectEvent(message, CommActions.ACTIONDETAILS)) { handleCommEventSync(message, CommActions.ACTIONDETAILS, this::onActionDetails); } }
Source:
public LZMACompressorInputStream(final InputStream inputStream) throws IOException { try { in = new LZMAInputStream(inputStream, MemoryLimit.getMemoryLimitInKb()); } catch (org.tukaani.xz.MemoryLimitException e) { throw new MemoryLimitException(e.getMemoryNeeded(), e.getMemoryLimit()); } }

Target:
public LZMACompressorInputStream(final InputStream inputStream) throws IOException { in = new LZMAInputStream(inputStream, -1); }
Source:
public ProfileDto updateProfileStatus(Integer userId, String statusName) { Profile profile = profileService.findProfileByUserLogin(userService.findUserById(userId).getLogin()); if(profile != null) { if(statusName.equals("Checked")) { profile.setChecked(true); } else { profile.setChecked(false); } profileService.saveProfile(profile); CheckedProfile checkedProfile = checkedProfileService.findCheckedProfileByProfileId(profile.getId()); if(checkedProfile == null) { checkedProfile = new CheckedProfile(); checkedProfile.setProfile(profile); } checkedProfile.setModerator(userService.findByLogin(SecurityContextHolder.getContext().getAuthentication().getName())); checkedProfile.setStatus(checkedStatusService.findByName(statusName)); checkedProfileService.save(checkedProfile); } return mapProfile(profile); }

Target:
public ProfileDto updateProfileStatus(Integer userId, String statusName) { Profile profile = profileService.findProfileByUserLogin(userService.findUserById(userId).getLogin()); if(profile != null) { if(statusName.equals("Checked")) { profile.setChecked(true); } else { profile.setChecked(false); } profileService.saveProfile(profile); CheckedProfile checkedProfile = checkedProfileService.findCheckedProfileByProfileId(profile.getId()); if(checkedProfile == null) { checkedProfile = new CheckedProfile(); checkedProfile.setProfile(profile); } checkedProfile.setModerator(userService.findByLogin(Util.getUserLogin())); checkedProfile.setStatus(checkedStatusService.findByName(statusName)); checkedProfileService.save(checkedProfile); } return mapProfile(profile); }
Source:
private String buildConfig(@NotNull String host) { String validName = getValidNameForSecret(host); StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append("host ") .append(host) .append("\n") .append("HostName ") .append(host) .append("\nIdentityFile ") .append(SSH_BASE_CONFIG_PATH) .append(validName) .append("/") .append(SSH_PRIVATE_KEY) .append("\n"); return stringBuilder.toString(); }

Target:
private String buildConfig(@NotNull String host) { return "host " + host + "\n" + "HostName " + host + "\nIdentityFile " + SSH_BASE_CONFIG_PATH + getValidNameForSecret(host) + "/" + SSH_PRIVATE_KEY + "\n"; }
Source:
private void writeDictionaryRowGroup(Block dictionary, int valueCount, LongInputStream dictionaryIdInputStream) { int[] dictionaryIdBuffer = new int[1024]; while (valueCount > 0) { int batchSize = Math.min(valueCount, dictionaryIdBuffer.length); try { dictionaryIdInputStream.nextIntVector(batchSize, dictionaryIdBuffer, 0); } catch (IOException e) { throw new RuntimeException(e); } DictionaryBlock dictionaryBlock = new DictionaryBlock(batchSize, dictionary, dictionaryIdBuffer); directColumnWriter.writeBlock(dictionaryBlock); valueCount -= batchSize; } checkState(valueCount == 0); }

Target:
private void writeDictionaryRowGroup(Block dictionary, int valueCount, LongInputStream dictionaryIdInputStream) { while (valueCount > 0) { int batchSize = Math.min(valueCount, 1024); int[] dictionaryIdBuffer = new int[batchSize]; try { dictionaryIdInputStream.nextIntVector(batchSize, dictionaryIdBuffer, 0); } catch (IOException e) { throw new UncheckedIOException("Unable to decode dictionary index stream", e); } DictionaryBlock dictionaryBlock = new DictionaryBlock(batchSize, dictionary, dictionaryIdBuffer); directColumnWriter.writeBlock(dictionaryBlock); valueCount -= batchSize; } checkState(valueCount == 0); }
Source:
protected Void visitExcept(Except node, Integer indent) { processRelation(node.getLeft(), indent); builder.append("EXCEPT "); if (node.isDistinct().isPresent()) { boolean isDistinct = node.isDistinct().get(); if (isDistinct) { builder.append("DISTINCT "); } else { builder.append("ALL "); } } processRelation(node.getRight(), indent); return null; }

Target:
protected Void visitExcept(Except node, Integer indent) { processRelation(node.getLeft(), indent); builder.append("EXCEPT "); node.isDistinct().map(distinct -> distinct ? builder.append("DISTINCT ") : builder.append("ALL ")); processRelation(node.getRight(), indent); return null; }
Source:
void duplicateAccountCreateFails() { verifyEndpointReturningObject(client -> client.createAccount(USERNAME_1, EMAIL_1, PASSWORD_1)); final CreateAccountResponse result = verifyEndpointReturningObject( client -> client.createAccount(USERNAME_1, EMAIL_1, PASSWORD_1)); assertThat(result, not(is(CreateAccountResponse.SUCCESS_RESPONSE))); }

Target:
void duplicateAccountCreateFails() { verifyEndpointReturningObject(client -> client.createAccount(USERNAME_1, EMAIL_1, PASSWORD_1)); final CreateAccountResponse result = verifyEndpointReturningObject( client -> client.createAccount(USERNAME_1, EMAIL_1, PASSWORD_1)); assertThat(result, is(not(CreateAccountResponse.SUCCESS_RESPONSE))); }
Source:
public Company get() { if (name == null) { name = dataMaster.getRandomValue(COMPANY_NAME); if (baseProducer.trueOrFalse()) { name += " " + dataMaster.getRandomValue(COMPANY_SUFFIX); } } if (domain == null) { domain = StringUtils.strip(StringUtils.deleteWhitespace(name.toLowerCase()), ".") + "." + dataMaster.getRandomValue(DOMAIN); } if (email == null) { email = dataMaster.getRandomValue(COMPANY_EMAIL); } if (vatIdentificationNumber == null) { vatIdentificationNumber = vatIdentificationNumberProvider.get(); } return new Company(name, domain, email, vatIdentificationNumber); }

Target:
public Company get() { if (name == null) { name = dataMaster.getRandomValue(COMPANY_NAME); if (baseProducer.trueOrFalse()) { name += " " + dataMaster.getRandomValue(COMPANY_SUFFIX); } } if (domain == null) { domain = TextUtils.stripAccents(StringUtils.strip(StringUtils.deleteWhitespace(name.toLowerCase()), ".").replace("/", "")) + "." + dataMaster.getRandomValue(DOMAIN); } if (email == null) { email = dataMaster.getRandomValue(COMPANY_EMAIL); } if (vatIdentificationNumber == null) { vatIdentificationNumber = vatIdentificationNumberProvider.get(); } return new Company(name, domain, email, vatIdentificationNumber); }
Source:
public void endVisitByUUID(final Visit visit) { visit.setStopDatetime(DateUtils.convertTime(System.currentTimeMillis(), DateUtils.OPEN_MRS_REQUEST_FORMAT)); Visit test = new Visit(); test.setStopDatetime(visit.getStopDatetime()); visitRepository.endVisitByUuid(visit.getUuid(), test, new DefaultVisitsCallback() { @Override public void onSuccess(String response) { addSubscription(visitDAO.getVisitByID(visit.getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vis -> { vis.setStopDatetime(response); visitDAO.saveOrUpdate(vis, vis.getPatient().getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(id -> moveToPatientDashboard()); })); } @Override public void onFailure(String errorMessage) { mVisitDashboardView.showErrorToast(errorMessage); } }); }

Target:
public void endVisitByUUID(final Visit visit) { visit.setStopDatetime(DateUtils.convertTime(System.currentTimeMillis(), DateUtils.OPEN_MRS_REQUEST_FORMAT)); Visit testVisit = new Visit(); testVisit.setStopDatetime(visit.getStopDatetime()); visitRepository.endVisitByUuid(visit.getUuid(), testVisit, new DefaultVisitsCallback() { @Override public void onSuccess(String response) { addSubscription(visitDAO.getVisitByID(visit.getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(visit -> { visit.setStopDatetime(response); visitDAO.saveOrUpdate(visit, visit.getPatient().getId()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(id -> moveToPatientDashboard()); })); } @Override public void onFailure(String errorMessage) { mVisitDashboardView.showErrorToast(errorMessage); } }); }
Source:
protected void initCoreModel(ManagementModel managementModel, Resource modelControllerResource) { if (modelInitializer != null) { modelInitializer.populateModel(managementModel); } System.setProperty("wildfly.test.boot.disable.rollback", "1"); initializer.initCoreModel(managementModel.getRootResource(), managementModel.getRootResourceRegistration(), modelControllerResource); }

Target:
protected void initCoreModel(ManagementModel managementModel, Resource modelControllerResource) { if (modelInitializer != null) { modelInitializer.populateModel(managementModel); } System.setProperty("jboss.as.test.disable.runtime", "1"); initializer.initCoreModel(managementModel.getRootResource(), managementModel.getRootResourceRegistration(), modelControllerResource); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_info) { AnalyticsTracker.get().trackEvent("Clicked on info menu item", null, null); new MaterialStyledDialog.Builder(MainActivity.this) .setTitle(getString(R.string.info_dialog_title)) .setDescription(getString(R.string.info_dialog_description)) .setIcon(R.mipmap.ic_launcher) .setHeaderColor(R.color.mapboxBlue) .withDivider(true) .setPositiveText(getString(R.string.info_dialog_positive_button_text)) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { AnalyticsTracker.get().trackEvent("Clicked on info menu dialog start learning button", null, null); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("<LINK_0>")); startActivity(intent); } }) .setNegativeText(getString(R.string.info_dialog_negative_button_text)) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { AnalyticsTracker.get().trackEvent("Clicked on info menu dialog not now button", null, null); } }) .show(); return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_info) { AnalyticsTracker.getInstance().trackEvent("Clicked on info menu item"); new MaterialStyledDialog.Builder(MainActivity.this) .setTitle(getString(R.string.info_dialog_title)) .setDescription(getString(R.string.info_dialog_description)) .setIcon(R.mipmap.ic_launcher) .setHeaderColor(R.color.mapboxBlue) .withDivider(true) .setPositiveText(getString(R.string.info_dialog_positive_button_text)) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { AnalyticsTracker.getInstance().trackEvent("Clicked on info menu dialog start learning button"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("<LINK_0>")); startActivity(intent); } }) .setNegativeText(getString(R.string.info_dialog_negative_button_text)) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { AnalyticsTracker.getInstance().trackEvent("Clicked on info menu dialog not now button"); } }) .show(); return true; } return super.onOptionsItemSelected(item); }
Source:
private void detach() { getTip().detach(); }

Target:
private void detach() { getTip().detach(); Widget w = options.getWidget(); if (w != null && RootPanel.isInDetachList(w)) { RootPanel.detachNow(w); } }