auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ConfigurationService createMockConfigurationServiceForOCDTests(List<String> registeredFactories, List<Tocd> registeredOcds, List<Component> registeredComponents) throws NoSuchFieldException { assertEquals(registeredFactories.size(), registeredOcds.size()); ScrService scrService = new ScrService() { @Override public Component[] getComponents(Bundle bundle) { return null; } @Override public Component[] getComponents(String componentName) { return null; } @Override public Component[] getComponents() { return registeredComponents.toArray(new Component[registeredComponents.size()]); } @Override public Component getComponent(long componentId) { return null; } }; final ConfigurationServiceImpl result = new ConfigurationServiceImpl(); result.setScrService(scrService); TestUtil.setFieldValue(result, "factoryPids", new HashSet<>(registeredFactories)); TestUtil.setFieldValue(result, "ocds", getOcdsMap(registeredFactories, registeredOcds)); return result; }

Target:
private OCDService createMockConfigurationServiceForOCDTests(List<String> registeredFactories, List<Tocd> registeredOcds, List<Component> registeredComponents) throws NoSuchFieldException { assertEquals(registeredFactories.size(), registeredOcds.size()); ScrService scrService = mock(ScrService.class); when(scrService.getComponents()) .thenReturn(registeredComponents.toArray(new Component[registeredComponents.size()])); final ConfigurationServiceImpl result = new ConfigurationServiceImpl(); result.setScrService(scrService); TestUtil.setFieldValue(result, "factoryPids", new HashSet<>(registeredFactories)); TestUtil.setFieldValue(result, "ocds", getOcdsMap(registeredFactories, registeredOcds)); return result; }
Source:
public static Bundle descriptionToBundle(MediaDescription desc) { Bundle ret = new Bundle(); if (desc == null) return ret; if (desc.getTitle() != null) { ret.putString(MediaMetadata.METADATA_KEY_TITLE, desc.getTitle().toString()); } if (desc.getSubtitle() != null) { ret.putString(MediaMetadata.METADATA_KEY_ARTIST, desc.getSubtitle().toString()); } if (desc.getDescription() != null) { ret.putString(MediaMetadata.METADATA_KEY_ALBUM, desc.getDescription().toString()); } if (desc.getExtras() != null) { try { ret.putAll(desc.getExtras()); } catch (BadParcelableException e) { if (DEBUG) Log.d(TAG, "MediaDescription contains invalid extras", e); } } if (ret.containsKey(GPM_KEY)) { if (DEBUG) Log.d(TAG, "MediaDescription contains GPM data"); ret.putAll(mediaMetadataToBundle((MediaMetadata) ret.get(GPM_KEY))); } return ret; }

Target:
public static Bundle descriptionToBundle(MediaDescription desc) { Bundle ret = new Bundle(); if (desc == null) return ret; if (desc.getTitle() != null) { ret.putString(MediaMetadata.METADATA_KEY_TITLE, desc.getTitle().toString()); } if (desc.getSubtitle() != null) { ret.putString(MediaMetadata.METADATA_KEY_ARTIST, desc.getSubtitle().toString()); } if (desc.getDescription() != null) { ret.putString(MediaMetadata.METADATA_KEY_ALBUM, desc.getDescription().toString()); } if (desc.getExtras() != null) { try { ret.putAll(desc.getExtras()); } catch (BadParcelableException e) { Log.d(TAG, "MediaDescription contains invalid extras", e); } } if (ret.containsKey(GPM_KEY)) { if (DEBUG) Log.d(TAG, "MediaDescription contains GPM data"); ret.putAll(mediaMetadataToBundle((MediaMetadata) ret.get(GPM_KEY))); } return ret; }
Source:
public SwitchingWrapper(OMXMLParserWrapper builder, OMContainer startNode, boolean cache, boolean preserveNamespaceContext) { this.navigator = new OMNavigator(startNode); this.builder = builder; this.rootNode = startNode; this.preserveNamespaceContext = preserveNamespaceContext; if (rootNode instanceof OMElement && ((OMElement)rootNode).getParent() instanceof OMDocument) { needToThrowEndDocument = true; } boolean resetCache = false; try { if (startNode instanceof OMSourcedElement && !cache && builder != null) { if (!builder.isCache()) { resetCache = true; } builder.setCache(true); } } catch (Throwable t) { log.error("Error in setting cache " + t.getMessage()); } currentNode = navigator.getNext(); updateNextNode(); if (resetCache) { builder.setCache(cache); } switchingAllowed = !cache; if (startNode instanceof OMDocument) { try { next(); } catch (XMLStreamException ex) { throw new OMException(ex); } } }

Target:
public SwitchingWrapper(OMXMLParserWrapper builder, OMContainer startNode, boolean cache, boolean preserveNamespaceContext) { this.navigator = new OMNavigator(startNode); this.builder = builder; this.rootNode = startNode; this.preserveNamespaceContext = preserveNamespaceContext; if (rootNode instanceof OMElement && ((OMElement)rootNode).getParent() instanceof OMDocument) { needToThrowEndDocument = true; } boolean resetCache = false; try { if (startNode instanceof OMSourcedElement && !cache && builder != null) { if (!builder.isCache()) { resetCache = true; } builder.setCache(true); } } catch (Throwable t) { log.error("Error in setting cache " + t.getMessage(), t); } currentNode = navigator.getNext(); updateNextNode(); if (resetCache) { builder.setCache(cache); } switchingAllowed = !cache; if (startNode instanceof OMDocument) { try { next(); } catch (XMLStreamException ex) { throw new OMException(ex); } } }
Source:
public Path getPathForMapInsensitive(String approxName) { String normalizedName = approxName.toLowerCase(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(customMapsDirectory)) { for (Path entry : stream) { if (entry.getFileName().toString().toLowerCase().equals(normalizedName)) { return entry; } } } catch (IOException e) { logger.warn("Could not check maps directory", e); } return null; }

Target:
public Path getPathForMapInsensitive(String approxName) { for (Path entry : noCatch(() -> Files.newDirectoryStream(getMapsDirectory(approxName)))) { if (entry.getFileName().toString().equalsIgnoreCase(approxName)) { return entry; } } return null; }
Source:
private String getType(Contentlet contentlet) { return contentlet.isHost() ? "SITE" : contentlet.getStructure().getName(); }

Target:
private String getType(Contentlet contentlet) { return contentlet != null && contentlet.isHost() ? SITE_EVENT_SUFFIX : contentlet.getStructure().getName(); }
Source:
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines) { assertLinesMatch(expectedLines, actualLines, () -> ""); }

Target:
static void assertLinesMatch(List<String> expectedLines, List<String> actualLines) { assertLinesMatch(expectedLines, actualLines, (Object) null); }
Source:
public boolean run() throws Exception { partitionCount = partitions.size(); List<BoundStatement> stmts; for (PartitionIterator iterator : partitions) while (iterator.hasNext()) stmts.add(bindRow(iterator.next())); rowCount += stmts.size(); for (int j = 0 ; j < stmts.size() ; j += 65535) { List<BoundStatement> substmts = stmts.subList(j, Math.min(j + stmts.size(), j + 65535)); Statement stmt; if (stmts.size() == 1) { stmt = substmts.get(0); } else { BatchStatement batch = new BatchStatement(batchType); batch.setConsistencyLevel(JavaDriverClient.from(cl)); batch.addAll(substmts); stmt = batch; } client.getSession().execute(stmt); } return true; }

Target:
public boolean run() throws Exception { List<BoundStatement> stmts = new ArrayList<>(); partitionCount = partitions.size(); for (PartitionIterator iterator : partitions) while (iterator.hasNext()) stmts.add(bindRow(iterator.next())); rowCount += stmts.size(); for (int j = 0 ; j < stmts.size() ; j += 65535) { List<BoundStatement> substmts = stmts.subList(j, Math.min(j + stmts.size(), j + 65535)); Statement stmt; if (stmts.size() == 1) { stmt = substmts.get(0); } else { BatchStatement batch = new BatchStatement(batchType); batch.setConsistencyLevel(JavaDriverClient.from(cl)); batch.addAll(substmts); stmt = batch; } client.getSession().execute(stmt); } return true; }
Source:
public void testGetFeedbackQuestionsForStudent() { ______TS("Get questions created for single student"); List<FeedbackQuestionAttributes> expectedQuestions = new ArrayList<FeedbackQuestionAttributes>(); expectedQuestions.add(getQuestionFromDatastore("qn1InSession1InCourse1")); expectedQuestions.add(getQuestionFromDatastore("qn2InSession1InCourse1")); expectedQuestions.add(getQuestionFromDatastore("custom.feedback.paths.student.question")); StudentAttributes student = studentsLogic.getStudentForEmail("idOfTypicalCourse1", "student1InCourse1@gmail.tmt"); List<FeedbackQuestionAttributes> actualQuestions = fqLogic.getFeedbackQuestionsForStudent( "First feedback session", "idOfTypicalCourse1", student); assertEquals(actualQuestions, expectedQuestions); }

Target:
public void testGetFeedbackQuestionsForStudent() { ______TS("Get questions created for single student"); List<FeedbackQuestionAttributes> expectedQuestions = new ArrayList<FeedbackQuestionAttributes>(); expectedQuestions.add(getQuestionFromDatastore("qn1InSession1InCourse1")); expectedQuestions.add(getQuestionFromDatastore("qn2InSession1InCourse1")); expectedQuestions.add(getQuestionFromDatastore("custom.feedback.paths.student.question")); expectedQuestions.add(getQuestionFromDatastore("custom.feedback.paths.team.question")); StudentAttributes student = studentsLogic.getStudentForEmail("idOfTypicalCourse1", "student5InCourse1@gmail.tmt"); List<FeedbackQuestionAttributes> actualQuestions = fqLogic.getFeedbackQuestionsForStudent( "First feedback session", "idOfTypicalCourse1", student); assertEquals(actualQuestions, expectedQuestions); }
Source:
public Optional<Date> getJobDeadline() { if (variables.containsKey(JOB_DDL)) { try { return Optional.of(ISODateTimeFormat.dateTimeNoMillis() .parseDateTime(variables.get(JOB_DDL).getValue()) .toDate()); } catch (Exception e) { LOGGER.info("Imposible to parse JOB_DDL GI variable as ISO8601 date", e); return Optional.empty(); } } else { return Optional.empty(); } }

Target:
public Optional<Date> getJobDeadline() { if (genericInformation.containsKey(JOB_DDL)) { try { return Optional.of(ISO8601DateUtil.toDate(genericInformation.get(JOB_DDL))); } catch (Exception e) { LOGGER.warn("Imposible to parse JOB_DDL GI variable as ISO8601 date", e); } } return Optional.empty(); }
Source:
private ProgramStateAtBlock(CfgBlock block, Map<Symbol, Set<Expression>> initialState) { this.block = block; this.in = initialState; init(); }

Target:
private ProgramStateAtBlock(CfgBlock block, Map<Symbol, Set<Expression>> initialState) { this.block = block; this.in = initialState; this.block.elements().forEach(element -> updateProgramState(element, out)); }
Source:
public void testBOM() throws Exception { File file = new File("src/test/resources/highlighting/bom.xml"); DefaultInputFile inputFile = new DefaultInputFile("bom.xml") .setLanguage(Xml.KEY) .setType(InputFile.Type.MAIN) .setAbsolutePath(file.getAbsolutePath()); DefaultFileSystem localFS = new DefaultFileSystem(new File(file.getParent())); localFS.add(inputFile).setWorkDir(tmpFolder.newFolder()); XmlFile xmlFile = new XmlFile(inputFile, localFS); List<HighlightingData> highlightingData = new XMLHighlighting(xmlFile, localFS.encoding()).getHighlightingData(); assertEquals(3, highlightingData.size()); assertData(highlightingData.get(0), 0, 6, "k"); }

Target:
public void testBOM() throws Exception { HighlightingData firstHighlightingData = getFirstHighlightingData("bom.xml"); assertData(firstHighlightingData, 0, 6, "k"); }
Source:
private void enterReloadMessageReadLoop(Socket accept) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(accept.getInputStream())); String line; while ((line = in.readLine()) != null) { DevModeHandler devModeHandler = DevModeHandler .getDevModeHandler(); if ("reload".equals(line) && devModeHandler != null && devModeHandler.getLiveReload() != null) { devModeHandler.getLiveReload().reload(); } } }

Target:
private void enterReloadMessageReadLoop(Socket accept) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader( accept.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = in.readLine()) != null) { DevModeHandler devModeHandler = DevModeHandler .getDevModeHandler(); if ("reload".equals(line) && devModeHandler != null && devModeHandler.getLiveReload() != null) { devModeHandler.getLiveReload().reload(); } } }
Source:
private boolean hasRelevantManagementRole(UserEntity user) { if (user.getRoles() == null) { return false ; } boolean hasOrganizationCreateUpdateDeleteRole = false; boolean hasEnvironmentCreateUpdateDeleteRoleExceptApplication = false ; for (UserRoleEntity userRoleEntity : user.getRoles()) { if (userRoleEntity.getPermissions() != null) { RoleScope currentScope = userRoleEntity.getScope() ; for (String permissionName : userRoleEntity.getPermissions().keySet()) { String permissionString = new String(userRoleEntity.getPermissions().get((permissionName))); boolean isCreateUpdateOrDelete = permissionString.contains("C") || permissionString.contains("U") || permissionString.contains("D"); if (currentScope.equals(RoleScope.ORGANIZATION) && isCreateUpdateOrDelete) { hasOrganizationCreateUpdateDeleteRole = true; } if (currentScope.equals(RoleScope.ENVIRONMENT) && !EnvironmentPermission.valueOf(permissionName).equals(EnvironmentPermission.APPLICATION) && isCreateUpdateOrDelete ) { hasEnvironmentCreateUpdateDeleteRoleExceptApplication = true; } } } } return hasOrganizationCreateUpdateDeleteRole || hasEnvironmentCreateUpdateDeleteRoleExceptApplication ; }

Target:
private boolean hasRelevantManagementRole(UserEntity user) { if (user.getRoles() == null) { return false ; } for (UserRoleEntity userRoleEntity : user.getRoles()) { if (userRoleEntity.getPermissions() != null) { RoleScope currentScope = userRoleEntity.getScope() ; for (String permissionName : userRoleEntity.getPermissions().keySet()) { String permissionString = new String(userRoleEntity.getPermissions().get((permissionName))); boolean isCreateUpdateOrDelete = permissionString.contains("C") || permissionString.contains("U") || permissionString.contains("D"); if (currentScope.equals(RoleScope.ORGANIZATION) && isCreateUpdateOrDelete) { return true ; } if (currentScope.equals(RoleScope.ENVIRONMENT) && !EnvironmentPermission.valueOf(permissionName).equals(EnvironmentPermission.APPLICATION) && isCreateUpdateOrDelete ) { return true; } } } } return false; }
Source:
public KmlLayer(GoogleMap map, InputStream stream, FragmentActivity activity, MarkerManager markerManager, PolygonManager polygonManager, PolylineManager polylineManager, GroundOverlayManager groundOverlayManager) throws XmlPullParserException, IOException { if (stream == null) { throw new IllegalArgumentException("KML InputStream cannot be null"); } KmlRenderer renderer = new KmlRenderer(map, activity, markerManager, polygonManager, polylineManager, groundOverlayManager); BufferedInputStream bis = new BufferedInputStream(stream); bis.mark(1024); ZipInputStream zip = new ZipInputStream(bis); try { KmlParser parser = null; ZipEntry entry = zip.getNextEntry(); if (entry != null) { while (entry != null) { if (parser == null && entry.getName().toLowerCase().endsWith(".kml")) { parser = parseKml(zip); } else { Bitmap bitmap = BitmapFactory.decodeStream(zip); if (bitmap != null) { renderer.cacheBitmap(entry.getName(), bitmap); } } entry = zip.getNextEntry(); } } else { bis.reset(); parser = parseKml(bis); } if (parser == null) { throw new IllegalArgumentException("KML not found in InputStream"); } renderer.storeKmlData(parser.getStyles(), parser.getStyleMaps(), parser.getPlacemarks(), parser.getContainers(), parser.getGroundOverlays()); storeRenderer(renderer); } finally { stream.close(); bis.close(); zip.close(); } }

Target:
public KmlLayer(GoogleMap map, InputStream stream, FragmentActivity activity, MarkerManager markerManager, PolygonManager polygonManager, PolylineManager polylineManager, GroundOverlayManager groundOverlayManager) throws XmlPullParserException, IOException { if (stream == null) { throw new IllegalArgumentException("KML InputStream cannot be null"); } KmlRenderer renderer = new KmlRenderer(map, activity, markerManager, polygonManager, polylineManager, groundOverlayManager); BufferedInputStream bis = new BufferedInputStream(stream); bis.mark(1024); ZipInputStream zip = new ZipInputStream(bis); try { KmlParser parser = null; ZipEntry entry = zip.getNextEntry(); if (entry != null) { HashMap<String, Bitmap> images = new HashMap<>(); while (entry != null) { if (parser == null && entry.getName().toLowerCase().endsWith(".kml")) { parser = parseKml(zip); } else { Bitmap bitmap = BitmapFactory.decodeStream(zip); if (bitmap != null) { images.put(entry.getName(), bitmap); } else { Log.w("KmlLayer", "Unsupported KMZ contents file type: " + entry.getName()); } } entry = zip.getNextEntry(); } if (parser == null) { throw new IllegalArgumentException("KML not found in InputStream"); } renderer.storeKmzData(parser.getStyles(), parser.getStyleMaps(), parser.getPlacemarks(), parser.getContainers(), parser.getGroundOverlays(), images); } else { bis.reset(); parser = parseKml(bis); renderer.storeKmlData(parser.getStyles(), parser.getStyleMaps(), parser.getPlacemarks(), parser.getContainers(), parser.getGroundOverlays()); } storeRenderer(renderer); } finally { stream.close(); bis.close(); zip.close(); } }
Source:
public void execute(ProcessContext context) throws Exception { WorkflowProcessInstance pi = context.getNodeInstance().getProcessInstance(); NodeInstance nodeInstance = findNodeByUniqueId(pi.getNodeInstances(), attachedToNodeId); if (nodeInstance != null) { ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).cancel(TIMED); } }

Target:
public void execute(ProcessContext context) throws Exception { WorkflowProcessInstance pi = context.getNodeInstance().getProcessInstance(); NodeInstance nodeInstance = findNodeByUniqueId(pi.getNodeInstances(), attachedToNodeId); if (nodeInstance != null) { ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).cancel(SKIPPED); } }
Source:
public void userOnDesktopCanAddPostWithoutTitle() { PostsListPage postList = new PostsListPage().open(); PostsCreatorDesktop postsCreator = postList.getPostCreatorDesktop(); postsCreator .clickPostCreator() .closeGuidelinesMessage() .fillPostContent("dupakupa123") .selectCategory(0); Assertion.assertTrue(postsCreator.isPostButtonActive()); postsCreator.clickSubmitButton(); Post post = postList.getPost(); post.getNewestPost() .ifPresent(webElement -> { Assertion.assertEquals("now", webElement.findElement(By.className("timestamp")).getText()); Assertion.assertEquals("", webElement.findElement(By.className("post-title")).getText()); }); }

Target:
public void userOnDesktopCanAddPostWithoutTitle() { final String description = createUniqueDescription(); PostsListPage postListPage = new PostsListPage().open(); PostsCreator postsCreator = postListPage.getPostsCreatorDesktop(); final CategoryPill categoryPill = fillPostCategoryWith(postsCreator, description); postsCreator.clickSubmitButton(); PostEntity postEntity = postListPage.getPost() .waitForPostToAppearWith(description) .getTheNewestPost(); assertThatPostWasAddedWith(postEntity, description, categoryPill.getName()); }
Source:
protected TextTemplate(String openArg, String closeArg, Object[] elements) { this.openArg = openArg; this.closeArg = closeArg; for (Object element : elements) { if (element instanceof Arg.Builder) { element = ((Arg.Builder) element).build(); } this.elements.add(element); if (element instanceof Arg) { Arg newArg = (Arg) element; newArg.openArg = this.openArg; newArg.closeArg = this.closeArg; Arg oldArg = this.arguments.get(newArg.name); if (oldArg != null && !oldArg.equals(newArg)) { throw new TextTemplateArgumentException("Tried to supply an unequal argument with a duplicate name \"" + newArg.name + "\" to TextTemplate."); } arguments.put(newArg.name, newArg); } } }

Target:
TextTemplate(String openArg, String closeArg, Object[] elements) { this.openArg = openArg; this.closeArg = closeArg; ImmutableList.Builder<Object> elementList = ImmutableList.builder(); Map<String, Arg> argumentMap = new HashMap<>(); for (Object element : elements) { if (element instanceof Arg.Builder) { element = ((Arg.Builder) element).build(); } if (element instanceof Arg) { Arg newArg = new Arg((Arg) element, this.openArg, this.closeArg); Arg oldArg = argumentMap.get(newArg.name); if (oldArg != null && !oldArg.equals(newArg)) { throw new TextTemplateArgumentException("Tried to supply an unequal argument with a duplicate name \"" + newArg.name + "\" to TextTemplate."); } argumentMap.put(newArg.name, newArg); element = newArg; } elementList.add(element); } this.elements = elementList.build(); this.arguments = ImmutableMap.copyOf(argumentMap); Text.Builder builder = null; for (Object element : this.elements) { builder = apply(element, builder); } this.text = Optional.ofNullable(builder).orElse(Text.builder()).build(); }
Source:
public Lower() { super(new Column[] { new Column("org/apache/tajo/storage/text", TajoDataTypes.Type.TEXT) }); }

Target:
public Lower() { super(new Column[] { new Column("text", TajoDataTypes.Type.TEXT) }); }
Source:
private PartitionIterator resolveWithReplicaFilteringProtection(E replicas, RepairedDataTracker repairedDataTracker) { ResolveContext firstPhaseContext = new ResolveContext(replicas); ResolveContext secondPhaseContext = new ResolveContext(replicas); ReplicaFilteringProtection<E> rfp = new ReplicaFilteringProtection<>(replicaPlan().keyspace(), command, replicaPlan().consistencyLevel(), queryStartNanoTime, firstPhaseContext.replicas); PartitionIterator firstPhasePartitions = resolveInternal(firstPhaseContext, rfp.mergeController(), i -> shortReadProtectedResponse(i, firstPhaseContext), UnaryOperator.identity()); PartitionIterators.consume(firstPhasePartitions); responses.clearUnsafe(); return resolveWithReadRepair(secondPhaseContext, rfp::queryProtectedPartitions, results -> command.rowFilter().filter(results, command.metadata(), command.nowInSec()), repairedDataTracker); }

Target:
private PartitionIterator resolveWithReplicaFilteringProtection(E replicas, RepairedDataTracker repairedDataTracker) { ResolveContext firstPhaseContext = new ResolveContext(replicas); ResolveContext secondPhaseContext = new ResolveContext(replicas); ReplicaFilteringProtection<E> rfp = new ReplicaFilteringProtection<>(replicaPlan().keyspace(), command, replicaPlan().consistencyLevel(), queryStartNanoTime, firstPhaseContext.replicas); PartitionIterator firstPhasePartitions = resolveInternal(firstPhaseContext, rfp.mergeController(), i -> shortReadProtectedResponse(i, firstPhaseContext), UnaryOperator.identity()); PartitionIterators.consume(firstPhasePartitions); firstPhasePartitions.close(); responses.clearUnsafe(); return resolveWithReadRepair(secondPhaseContext, rfp::queryProtectedPartitions, results -> command.rowFilter().filter(results, command.metadata(), command.nowInSec()), repairedDataTracker); }
Source:
public void verifySummaryText(String targetText) { waitForValueToBePresentInElementsAttributeByCss( summaryTextString, "value", targetText); PageObjectLogging.log("verifySummaryText", "verifying the summary shows " + targetText, true); }

Target:
public void verifySummaryText(String targetText) { waitForElementByElement(previewZoomer); waitForValueToBePresentInElementsAttributeByElement( summaryTextBox, "value", targetText ); PageObjectLogging.log( "verifySummaryText", "The summary shows " + targetText, true ); }
Source:
private Object toObject(byte[] arrayDate) throws IOException, ClassNotFoundException { ByteArrayInputStream bis = new ByteArrayInputStream(arrayDate); ObjectInputStream in = new ObjectInputStream(bis); return in.readObject(); }

Target:
private Object toObject(byte[] arrayDate) { ByteArrayInputStream bis = new ByteArrayInputStream(arrayDate); ObjectInputStream in = null; try { in = new ObjectInputStream(bis); return in.readObject(); } catch (IOException e) { log.error("Error while reading the registry", e); } catch (ClassNotFoundException e) { log.error("unable to access readObject method ", e); } finally { try { in.close(); bis.close(); } catch (IOException e) { log.error("Error while closing the registry stream", e); } } return null; }
Source:
public final boolean existPartitionMethod(final String databaseName, final String tableName) throws UndefinedTableException { try { final BlockingInterface stub = getStub(); final TableIdentifierProto request = buildTableIdentifier(databaseName, tableName); final ReturnState state = stub.existPartitionMethod(null, request); if (isThisError(state, UNDEFINED_PARTITION_METHOD)) { return false; } throwsIfThisError(state, UndefinedTableException.class); ensureOk(state); return true; } catch (ServiceException e) { throw new RuntimeException(e); } }

Target:
public final boolean existPartitionMethod(final String databaseName, final String tableName) throws UndefinedDatabaseException, UndefinedTableException { try { final BlockingInterface stub = getStub(); final TableIdentifierProto request = buildTableIdentifier(databaseName, tableName); final ReturnState state = stub.existPartitionMethod(null, request); if (isThisError(state, UNDEFINED_PARTITION_METHOD)) { return false; } throwsIfThisError(state, UndefinedDatabaseException.class); throwsIfThisError(state, UndefinedTableException.class); ensureOk(state); return true; } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); String action = getIntent().getAction(); Timber.d(String.format("action = %s", action)); if(action != null) switch (action) { case Intent.ACTION_VIEW: initalizeDeck(getIntent().getExtras()); break; default: } super.onCreate(savedInstanceState); }

Target:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); if (Intent.ACTION_VIEW.equals(getIntent().getAction())) { Timber.d("onCreate() :: received Intent with action = %s", getIntent().getAction()); selectDeckFromExtra(); } super.onCreate(savedInstanceState); }
Source:
public void activate(Map<String, Object> properties) { String cipherTarget = (String) properties.getOrDefault("CIPHER_TARGET", SymmetricKeyCipher.CIPHER_ID); storageCipher = allAvailableStorageCiphers.stream() .filter(cipher -> cipher.getUniqueCipherId().equals(cipherTarget)).findFirst(); logger.debug("Using Cipher: {}", storageCipher.orElse(null)); loadAllHandlesAndTokens(); }

Target:
public void activate(Map<String, Object> properties) throws GeneralSecurityException { String cipherTarget = (String) properties.getOrDefault("CIPHER_TARGET", SymmetricKeyCipher.CIPHER_ID); storageCipher = allAvailableStorageCiphers.stream() .filter(cipher -> cipher.getUniqueCipherId().equals(cipherTarget)).findFirst(); logger.debug("Using Cipher: {}", storageCipher .orElseThrow(() -> new GeneralSecurityException("No StorageCipher with target=" + cipherTarget))); }
Source:
public Model resolveRawModel( final ProjectVersionRef ref ) throws ManipulationException { Transfer transfer; try { transfer = galleyWrapper.resolveArtifact( ref.asPomArtifact() ); } catch ( final TransferException e ) { throw new ManipulationException( "Failed to resolve POM: %s.%n--> %s", e, ref, e.getMessage() ); } if ( transfer == null ) { throw new ManipulationException( "Failed to resolve POM: " + ref.asPomArtifact() ); } try (InputStream in = transfer.openInputStream()) { return new MavenXpp3Reader().read( in ); } catch ( final IOException | XmlPullParserException e ) { throw new ManipulationException( "Failed to build model for POM: %s.%n--> %s", e, ref, e.getMessage() ); } }

Target:
public Model resolveRawModel( final ProjectVersionRef ref ) throws ManipulationException { Transfer transfer; try { transfer = galleyWrapper.resolveArtifact( ref.asPomArtifact() ); } catch ( final TransferException e ) { throw new ManipulationException( "Failed to resolve POM: " + ref + "." + System.lineSeparator() + "--> " + e.getMessage(), e ); } if ( transfer == null ) { throw new ManipulationException( "Failed to resolve POM: " + ref.asPomArtifact() ); } try (InputStream in = transfer.openInputStream()) { return new MavenXpp3Reader().read( in ); } catch ( final IOException | XmlPullParserException e ) { throw new ManipulationException( "Failed to build model for POM: " + ref + "." + System.lineSeparator() + "--> " + e.getMessage(), e ); } }
Source:
public void processStream(final KafkaReporter kafkaReporter, FlinkBenchConfig config) throws Exception{ createDataStream(config); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Tuple2<String, String>> dataStream = env.addSource(getDataStream()); dataStream.rebalance().map((new MapFunction<Tuple2<String, String>, Tuple2<String, String>>() { @Override public Tuple2<String, String> map(Tuple2<String, String> value) throws Exception { kafkaReporter.report(Long.parseLong(value.f0), System.currentTimeMillis()); return value; } })); env.execute("Identity job"); }

Target:
public void processStream(final KafkaReporter kafkaReporter, FlinkBenchConfig config) throws Exception{ createDataStream(config); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Tuple2<String, String>> dataStream = env.addSource(getDataStream()); dataStream.rebalance().map((new MapFunction<Tuple2<String, String>, Tuple2<String, String>>() { @Override public Tuple2<String, String> map(Tuple2<String, String> value) throws Exception { kafkaReporter.report(Long.parseLong(value.f0), System.currentTimeMillis()); return value; } })); env.execute("Repartition job"); }
Source:
private void revokeAccessToken() { URI ssoRevokeURI = null; if (ssoRevokeUrl != null) { ssoRevokeURI = SsoUtils.buildUrl(ssoRevokeUrl); } else { if (ssoToken != null) { ssoRevokeURI = SsoUtils.buildSsoRevokeUrl(url, ssoToken); } } if (ssoRevokeURI != null) { JsonNode node = getSsoResponse(ssoRevokeURI); if (node.isArray()) { node = node.get(0); } if (node.get("error") != null) { throw new RuntimeException( String.format( "Error during SSO token revoke %1$s : %2$s", node.get("error_code"), node.get("error") ) ); } } }

Target:
private void revokeAccessToken() { URI ssoRevokeURI = ssoRevokeUrl != null ? SsoUtils.buildUrl(ssoRevokeUrl) : ssoToken != null ? SsoUtils.buildSsoRevokeUrl(url, ssoToken) : null; if (ssoRevokeURI != null) { JsonNode node = getSsoResponse(ssoRevokeURI); if (node.isArray()) { node = node.get(0); } if (node.get("error") != null) { throw new RuntimeException( String.format( "Error during SSO token revoke %1$s : %2$s", node.get("error_code"), node.get("error") ) ); } } }
Source:
private static void calculate(CalculationRunner runner) { CdsTrade cds = createSingleNameCds(); List<Trade> trades = ImmutableList.of(cds); List<Column> columns = ImmutableList.of( Column.of(Measures.PRESENT_VALUE)); LocalDate valuationDate = LocalDate.of(2014, 10, 16); ImmutableMarketDataBuilder baseMarketDataBuilder = ImmutableMarketData.builder(valuationDate); loadBaseYieldCurves(baseMarketDataBuilder); loadBaseSingleNameCreditCurves(baseMarketDataBuilder); ImmutableMarketData baseMarketData = baseMarketDataBuilder.build(); ScenarioDefinition scenarios = buildScenarios(baseMarketData); CalculationFunctions functions = StandardComponents.calculationFunctions(); CalculationRules rules = CalculationRules.of(functions); ReferenceData refData = ReferenceData.standard(); MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData); ScenarioMarketData scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), baseMarketData, refData, scenarios); Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData); CurrencyValuesArray pvVector = (CurrencyValuesArray) results.get(0, 0).getValue(); outputCurrencyValues("PVs", pvVector); CurrencyValuesArray pnlVector = getSortedPnls(pvVector); outputCurrencyValues("Scenario PnLs", pnlVector); double var95 = SampleInterpolationQuantileMethod.DEFAULT.quantileFromUnsorted(0.05, pnlVector.getValues()); System.out.println(Messages.format("95% VaR: {}", var95)); }

Target:
private static void calculate(CalculationRunner runner) { CdsTrade cds = createSingleNameCds(); List<Trade> trades = ImmutableList.of(cds); List<Column> columns = ImmutableList.of( Column.of(Measures.PRESENT_VALUE)); ImmutableMarketData baseMarketData = buildBaseMarketData(); ScenarioDefinition scenarios = buildScenarios(baseMarketData); CalculationFunctions functions = StandardComponents.calculationFunctions(); CalculationRules rules = CalculationRules.of(functions); ReferenceData refData = ReferenceData.standard(); MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData); ScenarioMarketData scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), baseMarketData, refData, scenarios); Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData); CurrencyValuesArray pvVector = (CurrencyValuesArray) results.get(0, 0).getValue(); outputCurrencyValues("PVs", pvVector); CurrencyValuesArray pnlVector = getSortedPnls(pvVector); outputCurrencyValues("Scenario PnLs", pnlVector); double var95 = SampleInterpolationQuantileMethod.DEFAULT.quantileFromSorted(0.05, pnlVector.getValues()); System.out.println(Messages.format("95% VaR: {}", var95)); }
Source:
HttpResponse sendGetRequest(URI backupUri) { HttpResponse httpResponse = null; HttpGet get = new HttpGet(backupUri); HttpClient client = httpBuilder.get().build(); try { LOGGER.debug("Sending request to {}", backupUri); httpResponse = client.execute(get); } catch (IOException e) { LOGGER.debug("Error during request. Returning null response."); } return httpResponse; }

Target:
HttpResponse sendGetRequest(URI backupUri) { HttpResponse httpResponse = null; HttpGet get = new HttpGet(backupUri); HttpClient client = httpBuilder.get().build(); try { LOGGER.debug("Sending request to {}", backupUri); httpResponse = client.execute(get); } catch (IOException e) { LOGGER.debug("Error during request. Returning null response.", e); } return httpResponse; }
Source:
protected static boolean createDirectoryIfNotExist(Path path) { File dir = path.toFile(); if(!dir.exists()) { if(!dir.mkdir()) { logger.warn("Was unable to make a directory called " + dir); return false; } } if(dir.exists() && !dir.isDirectory()) { logger.warn("Was unable to make a directory because" + " there is a file called " + dir); return false; } return true; }

Target:
protected static boolean createDirectoryIfNotExist(Path path) { File dir = path.toFile(); if(!dir.exists()) { if(!dir.mkdirs()) { logger.warn("Was unable to make a directory called " + dir); return false; } } if(dir.exists() && !dir.isDirectory()) { logger.warn("Was unable to make a directory because" + " there is a file called " + dir); return false; } return true; }
Source:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); this.targetContentEncoding = targetContentEncoding; this.contentEncoder = contentEncoder; }

Target:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { this.targetContentEncoding = ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); this.contentEncoder = ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); }
Source:
public void testComparePercentVerificationBetweenTwoSets() { Buffer buffer = (Buffer) store; buffer.start(); List<Write> stored1 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); List<Write> stored2 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); int initialSize = stored2.size(); Random rand = new Random(); int transferSize = rand.nextInt(stored1.size()); for(int i = 0; i < transferSize; i++) { stored2.add(stored1.get(i)); } Iterator<Write> iterator = stored2.iterator(); while(iterator.hasNext()) { buffer.verifyFast(iterator.next()); } float percentVerifyScans = Reflection.call(buffer, "getPercentVerifyScans"); float percentTransferred = ((float) transferSize) / (transferSize + initialSize); Assert.assertTrue(percentVerifyScans >= percentTransferred); }

Target:
public void testComparePercentVerificationBetweenTwoSets() { Buffer buffer = (Buffer) store; List<Write> stored1 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); List<Write> stored2 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); int initialSize = stored2.size(); Random rand = new Random(); int transferSize = rand.nextInt(stored1.size()); for(int i = 0; i < transferSize; i++) { stored2.add(stored1.get(i)); } Iterator<Write> iterator = stored2.iterator(); while(iterator.hasNext()) { Write write = iterator.next(); buffer.verify(write.getKey().toString(), write.getValue().getTObject(), write.getRecord().longValue()); } float percentVerifyScans = Reflection.call(buffer, "getPercentVerifyScans"); float percentTransferred = ((float) transferSize) / (transferSize + initialSize); Assert.assertTrue(percentVerifyScans >= percentTransferred); }
Source:
public static GoExpression getExpression(@NotNull GoIndexOrSliceExpr slice) { List<GoExpression> leftExpressions = getExpressionsBefore(slice.getExpressionList(), slice.getLbrack()); return leftExpressions.isEmpty() ? null : leftExpressions.get(0); }

Target:
public static GoExpression getExpression(@NotNull GoIndexOrSliceExpr slice) { List<GoExpression> leftExpressions = getExpressionsBefore(slice.getExpressionList(), slice.getLbrack()); return ContainerUtil.getFirstItem(leftExpressions); }
Source:
public void close() throws Exception { try { if (jobBundleFactory != null) { jobBundleFactory.close(); } } finally { jobBundleFactory = null; } try { if (sharedResources != null) { sharedResources.close(); } } finally { sharedResources = null; } environmentManager.close(); }

Target:
public void close() throws Exception { try { if (jobBundleFactory != null) { jobBundleFactory.close(); } } finally { jobBundleFactory = null; } try { if (sharedResources != null) { if (sharedResources.getResourceHandle().release()) { sharedResources.close(); } } else { environmentManager.close(); } } finally { sharedResources = null; } }
Source:
public Long getLastUpdateTime() { String rval = (String) globalSettings.get( GlobalSettingsKey.JTTP_PLUGIN_SETTINGS_KEY_PREFIX + GlobalSettingsKey.JTTP_UPDATE_NOTIFIER_LAST_UPDATE); return rval == null ? null : Long.parseLong(rval); }

Target:
public Long getLastUpdateTime() { String lastUpdateInMilisec = (String) globalSettings.get( GlobalSettingsKey.JTTP_PLUGIN_SETTINGS_KEY_PREFIX + GlobalSettingsKey.JTTP_UPDATE_NOTIFIER_LAST_UPDATE); return lastUpdateInMilisec == null ? null : Long.parseLong(lastUpdateInMilisec); }
Source:
public List<BusinessService> search(BusinessServiceSearchCriteria businessServiceSearchCriteria) { if (businessServiceSearchCriteria == null) { throw new IllegalArgumentException("Search criteria must not be null"); } return businessServiceSearchCriteria.apply(this, getAllBusinessServices()); }

Target:
public List<BusinessService> search(BusinessServiceSearchCriteria businessServiceSearchCriteria) { Objects.requireNonNull(businessServiceSearchCriteria); return businessServiceSearchCriteria.apply(this, getAllBusinessServices()); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent i = getParentActivityIntent().putExtra("forceMainMenu", true); navigateUpTo(i); return super.onOptionsItemSelected(item); case R.id.display_parameters: AnalyticsHelper.sendEventHit("Filters", AnalyticsHelper.CLICK, "YES"); createDialog(); default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent i = getParentActivityIntent().putExtra("forceMainMenu", true); NavUtils.navigateUpTo(this, i); return super.onOptionsItemSelected(item); case R.id.display_parameters: AnalyticsHelper.sendEventHit("Filters", AnalyticsHelper.CLICK, "YES"); createDialog(); default: return super.onOptionsItemSelected(item); } }
Source:
private List<Activity> buildActivities(List<WebElement> activities) { activities.forEach(element -> this.activities.add(new Activity(element))); return this.activities; }

Target:
private List<Activity> buildActivities(List<WebElement> activities) { return activities.stream().map(Activity::new).collect(Collectors.toList()); }
Source:
public String toString() { if (script != null) { return "" + new String(getHash()) + "\n" + script; } else { return "" + new String(getHash()) + "\n" + url; } }

Target:
public String toString() { return "" + new String(getHash()) + "\n" + (script != null ? script : url); }
Source:
public InputStream createInputStream(long offset) throws IOException { if (doesExist()) { return file.createInputStream(); } StorageUtils.LOG.FINE("Reading file '%s'", childName); return new ByteArrayInputStream(EMPTY_BUFFER); }

Target:
public InputStream createInputStream(long offset) throws IOException { if (doesExist()) { return file.createInputStream(); } StorageUtils.LOG.FINE("Layer3/FTP: Downloading file '%s' from '%s'", childName, parent); return new ByteArrayInputStream(EMPTY_BUFFER); }
Source:
public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) { this.context = context; this.attrs = attributeSet; this.defStyle = defStyle; if (attributeSet != null) { key = attributeSet.getAttributeValue(ResourceLoader.ANDROID_NS, "key"); if (key != null && key.startsWith("@")) { final ResourceLoader resourceLoader = shadowOf(context.getResources()).getResourceLoader(); key = resourceLoader.getValue(new ResName(key.replace("@", "")), "").asString(); } } }

Target:
public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) { this.context = context; this.attrs = attributeSet; this.defStyle = defStyle; if (attributeSet != null) { final TypedArray typedArray = context.obtainStyledAttributes(attributeSet, com.android.internal.R.styleable.Preference); key = typedArray.getString(com.android.internal.R.styleable.Preference_key); } }
Source:
public void setShouldRecognizeText(boolean shouldRecognizeText) { if (shouldRecognizeText && !mTextRecognizer) { setupTextRecongnizer(); } this.mShouldRecognizeText = shouldRecognizeText; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }

Target:
public void setShouldRecognizeText(boolean shouldRecognizeText) { if (shouldRecognizeText && mTextRecognizer == null) { setupTextRecongnizer(); } this.mShouldRecognizeText = shouldRecognizeText; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }
Source:
public void run() { ConnectionFactory cf = new ConnectionFactory(Constants.DEFAULT_URL); try { Connection conn = cf.createConnection(); FPublisherTransportFactory publisherFactory = new FNatsPublisherTransport.Factory(conn); FSubscriberTransportFactory subscriberFactory = new FNatsSubscriberTransport.Factory(conn); FScopeProvider provider = new FScopeProvider(publisherFactory, subscriberFactory, protocolFactory); EventsSubscriber.Iface subscriber = new EventsSubscriber.Client(provider); try { subscriber.subscribeEventCreated("*", "*", "call", Integer.toString(port), (context, event) -> { System.out.format("received " + context + " : " + event); EventsPublisher.Iface publisher = new EventsPublisher.Client(provider); try { publisher.open(); String preamble = context.getRequestHeader(utils.PREAMBLE_HEADER); String ramble = context.getRequestHeader(utils.RAMBLE_HEADER); event = new Event(1, "received call"); publisher.publishEventCreated(new FContext("Call"), preamble, ramble, "response", Integer.toString(port), event); } catch (TException e) { System.out.println("Error opening publisher to respond" + e.getMessage()); } }); } catch (TException e) { System.out.println("Error subscribing" + e.getMessage()); } System.out.println("Subscriber started..."); } catch (TimeoutException | IOException e) { System.out.println("Error connecting to nats" + e.getMessage()); } }

Target:
public void run() { ConnectionFactory cf = new ConnectionFactory(Constants.DEFAULT_URL); try { Connection conn = cf.createConnection(); FPublisherTransportFactory publisherFactory = new FNatsPublisherTransport.Factory(conn); FSubscriberTransportFactory subscriberFactory = new FNatsSubscriberTransport.Factory(conn); FScopeProvider provider = new FScopeProvider(publisherFactory, subscriberFactory, protocolFactory); EventsSubscriber.Iface subscriber = new EventsSubscriber.Client(provider); try { subscriber.subscribeEventCreated("*", "*", "call", Integer.toString(port), (context, event) -> { System.out.format("received " + context + " : " + event); EventsPublisher.Iface publisher = new EventsPublisher.Client(provider); try { publisher.open(); String preamble = context.getRequestHeader(utils.PREAMBLE_HEADER); if (preamble == null || "".equals(preamble)) { System.out.println("Client did not provide preamble header"); return; } String ramble = context.getRequestHeader(utils.RAMBLE_HEADER); if (ramble == null || "".equals(ramble)) { System.out.println("Client did not provide ramble header"); return; } event = new Event(1, "received call"); publisher.publishEventCreated(new FContext("Call"), preamble, ramble, "response", Integer.toString(port), event); } catch (TException e) { System.out.println("Error opening publisher to respond" + e.getMessage()); } }); } catch (TException e) { System.out.println("Error subscribing" + e.getMessage()); } System.out.println("Subscriber started..."); } catch (TimeoutException | IOException e) { System.out.println("Error connecting to nats" + e.getMessage()); } }
Source:
public void handleUnimprovedMinutesSpentInputChange( ChangeEvent event ) { try { Long value = unimprovedMinutesSpentInput.getValue().isEmpty() ? null : Long.parseLong( unimprovedMinutesSpentInput.getValue() ); presenter.onUnimprovedMinutesSpentChange( value ); } catch ( NumberFormatException e ) { } }

Target:
public void handleUnimprovedMinutesSpentInputChange( ChangeEvent event ) { boolean isNumeric = unimprovedMinutesSpentInput.getValue().matches( "\\d+" ); if (isNumeric) { presenter.onUnimprovedMinutesSpentChange( Long.parseLong( unimprovedMinutesSpentInput.getValue() ) ); } else { presenter.onUnimprovedMinutesSpentChange( 0l ); unimprovedMinutesSpentInput.setValue( "0" ); } }
Source:
public void before() { super.before(); super.tableEnv().executeSql(String.format( "create table orcFilterTable (" + "x string," + "y int," + "a int," + "b bigint," + "c boolean," + "d string" + ") with (" + "'connector' = 'filesystem'," + "'path' = '%s'," + "%s)", super.resultPath(), String.join(",\n", formatProperties()))); }

Target:
public void before() { super.before(); super.tableEnv().executeSql(String.format( "create table orcFilterTable (" + "x string," + "y int," + "a int," + "b bigint," + "c boolean," + "d string," + "e decimal(8,4)," + "f date," + "g timestamp" + ") with (" + "'connector' = 'filesystem'," + "'path' = '%s'," + "%s)", super.resultPath(), String.join(",\n", formatProperties()))); }
Source:
public ITimeEvent splitAfter(long splitTime) { throw new UnsupportedOperationException(); }

Target:
public ITimeEvent splitAfter(long splitTime) { return (splitTime < fTime + fDuration ? new TimeEvent(getEntry(), Math.max(fTime, splitTime), fDuration - Math.max(0, splitTime - fTime)) : null); }