auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public WebTarget setupAuthentication(WebTarget target) { if (username != null && password != null) { logger.trace("[setupAuthentication] {}@{}", username, password); target.register(HttpAuthenticationFeature.basic(username, password)); return target; } else { throw new ServerErrorException("Unable to setup authentication", Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
public WebTarget setupAuthentication(WebTarget target) { if (username != null && password != null) { logger.trace("[setupAuthentication] {}", username); target.register(HttpAuthenticationFeature.basic(username, password)); return target; } else { throw new ServerErrorException("Unable to setup authentication", Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
public void handleChildCommands() { if (getCallback() != null) { List<Guid> childCommands = CommandCoordinatorUtil.getChildCommandIds(getCommandId()); List<VdcActionParametersBase> parameters = new LinkedList<>(); for (Guid id : childCommands) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(id); if (command.getParameters().getEndProcedure() == EndProcedure.BY_PARENT || command.getParameters().getEndProcedure() == EndProcedure.PARENT_MANAGED) { command.getParameters().setEndProcedure(EndProcedure.PARENT_MANAGED); command.getParameters().setCommandType(command.getActionType()); parameters.add(command.getParameters()); } } getParameters().setImagesParameters(parameters); } }

Target:
public void handleChildCommands() { if (getCallback() != null) { List<Guid> childCommands = CommandCoordinatorUtil.getChildCommandIds(getCommandId()); List<VdcActionParametersBase> parameters = new LinkedList<>(); for (Guid id : childCommands) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(id); if (command.getParameters().getEndProcedure() == EndProcedure.PARENT_MANAGED || command.getParameters().getEndProcedure() == EndProcedure.FLOW_MANAGED) { command.getParameters().setEndProcedure(EndProcedure.FLOW_MANAGED); command.getParameters().setCommandType(command.getActionType()); parameters.add(command.getParameters()); } } getParameters().setImagesParameters(parameters); } }
Source:
public void setZeroValue() { percentageBarB.setVisible(false); percentageBarA.setVisible(true); percentageBarA.setTitle(title); percentageBarA.setStyleName(style.empty()); percentageBarA.setWidth(FULL_WIDTH + "%"); percentageLabelA.setText(ZERO); percentageLabelA.setStyleName(style.percentageLabelBlack()); }

Target:
public void setZeroValue() { percentageBarB.setVisible(false); percentageBarB.setWidth("0px"); percentageBarA.setVisible(true); percentageBarA.setTitle(title); percentageBarA.setStyleName(style.empty()); percentageBarA.setWidth(FULL_WIDTH + "%"); percentageLabelA.setText(ZERO); percentageLabelA.setStyleName(style.percentageLabelBlack()); }
Source:
private List<Device> getDetailedDevices() { List<Device> deviceList = new LinkedList<Device>(); JsonObject result = connMan.getDigitalSTROMAPI().query2(connMan.getSessionToken(), GET_DETAILD_DEVICES); if (result != null && result.isJsonObject()) { if (result.getAsJsonObject().get("zone0").isJsonObject()) { result = result.getAsJsonObject().get("zone0").getAsJsonObject(); for (Entry<String, JsonElement> entry : result.entrySet()) { if (!(entry.getKey().equals(JSONApiResponseKeysEnum.ZONE_ID.getKey()) && entry.getKey().equals(JSONApiResponseKeysEnum.NAME.getKey())) && entry.getValue().isJsonObject()) { deviceList.add(new DeviceImpl(entry.getValue().getAsJsonObject())); } } } } return deviceList; }

Target:
private List<Device> getDetailedDevices() { List<Device> deviceList = new LinkedList<Device>(); JsonObject result = connMan.getDigitalSTROMAPI().query2(connMan.getSessionToken(), GET_DETAILD_DEVICES); if (result != null && result.isJsonObject()) { if (result.getAsJsonObject().get(GeneralLibConstance.QUERY_BROADCAST_ZONE_STRING).isJsonObject()) { result = result.getAsJsonObject().get(GeneralLibConstance.QUERY_BROADCAST_ZONE_STRING) .getAsJsonObject(); for (Entry<String, JsonElement> entry : result.entrySet()) { if (!(entry.getKey().equals(JSONApiResponseKeysEnum.ZONE_ID.getKey()) && entry.getKey().equals(JSONApiResponseKeysEnum.NAME.getKey())) && entry.getValue().isJsonObject()) { deviceList.add(new DeviceImpl(entry.getValue().getAsJsonObject())); } } } } return deviceList; }
Source:
private List<String> getRepoTags() { if (projectPreferences != null) { String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG, ICreaterepoConstants.EMPTY_STRING); if (!tagPref.isEmpty()) { return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER)); } } return ICreaterepoConstants.EMPTY_LIST; }

Target:
private List<String> getRepoTags() { if (projectPreferences != null) { String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG, ICreaterepoConstants.EMPTY_STRING); if (!tagPref.isEmpty()) { return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER)); } } return Collections.EMPTY_LIST; }
Source:
public Webhook(String componentUuid, @Nullable String ceTaskUuid, @Nullable String analysisUuid, String name, String url) { this.componentUuid = requireNonNull(componentUuid); this.ceTaskUuid = ceTaskUuid; this.analysisUuid = requireNonNull(analysisUuid); this.name = requireNonNull(name); this.url = requireNonNull(url); }

Target:
public Webhook(String componentUuid, @Nullable String ceTaskUuid, @Nullable String analysisUuid, String name, String url) { this.componentUuid = requireNonNull(componentUuid); this.ceTaskUuid = ceTaskUuid; this.analysisUuid = analysisUuid; this.name = requireNonNull(name); this.url = requireNonNull(url); }
Source:
public static boolean isValidEmail(String emailAddress) { final String regex = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-+]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"; return emailAddress.matches(regex); }

Target:
public static boolean isValidEmail(String emailAddress) { return emailAddress.matches(EMAIL_VALIDATION_REGEX); }
Source:
public void syncData(String storageDomainId, String geoRepSessionId) { try { StorageDomain storageDomain = storageDomainDao.get(new Guid(storageDomainId)); if (storageDomain == null) { log.error("No storage domain found"); return; } GlusterGeoRepSession session = geoRepDao.getById(new Guid(geoRepSessionId)); if (session == null) { log.error("No geo-replication session found"); return; } backend.runInternalAction(VdcActionType.GlusterStorageSync, new GlusterStorageSyncCommandParameters(storageDomain.getId(), session.getId()), ExecutionHandler.createInternalJobContext()); } catch (Exception e) { log.error("Error running dr sync", e); } }

Target:
public void syncData(String storageDomainId, String geoRepSessionId) { try { StorageDomain storageDomain = storageDomainDao.get(new Guid(storageDomainId)); if (storageDomain == null) { log.error("No storage domain found for id '{}'", storageDomainId); return; } GlusterGeoRepSession session = geoRepDao.getById(new Guid(geoRepSessionId)); if (session == null) { log.error("No geo-replication session found for id '{}'", geoRepSessionId); return; } backend.runInternalAction(VdcActionType.GlusterStorageSync, new GlusterStorageSyncCommandParameters(storageDomain.getId(), session.getId()), ExecutionHandler.createInternalJobContext()); } catch (Exception e) { log.error("Error running dr sync", e); } }
Source:
public void verifyUserLoggedIn(final String userName) { changeImplicitWait(0, TimeUnit.MILLISECONDS); try { if (driver.findElements(By.cssSelector("#PreviewFrame")).size() > 0) { driver.switchTo().frame("PreviewFrame"); } if (driver.findElements(MERCURY_SKIN).size() > 0) { wait.forElementClickable(MERCURY_NAV_ICON); driver.findElement(MERCURY_NAV_ICON).click(); wait.forElementVisible(By.cssSelector( LOGGED_IN_USER_SELECTOR_MERCURY.replace("%userName%", userName.replace(" ", "_")))); wait.forElementClickable(MERCURY_NAV_ICON); driver.findElement(MERCURY_NAV_ICON).click(); } else { wait.forElementVisible(By.cssSelector(LOGGED_IN_USER_SELECTOR_OASIS)); WebElement avatar = driver.findElement(By.cssSelector(LOGGED_IN_USER_SELECTOR_OASIS)); String loggedInUserName = avatar.getAttribute("alt"); if (!loggedInUserName.equals(userName)) { throw new IllegalArgumentException( "Invalid user, expected " + userName + ", but found: " + loggedInUserName); } } } finally { restoreDefaultImplicitWait(); driver.switchTo().defaultContent(); } PageObjectLogging.log("verifyUserLoggedIn", "user " + userName + " logged in", true); }

Target:
public void verifyUserLoggedIn(final String userName) { changeImplicitWait(0, TimeUnit.MILLISECONDS); try { if (driver.findElements(By.cssSelector("#PreviewFrame")).size() > 0) { driver.switchTo().frame("PreviewFrame"); } if (driver.findElements(MERCURY_SKIN).size() > 0) { wait.forElementClickable(MERCURY_NAV_ICON); driver.findElement(MERCURY_NAV_ICON).click(); wait.forElementVisible(By.cssSelector( LOGGED_IN_USER_SELECTOR_MERCURY.replace("%userName%", userName.replace(" ", "_")))); wait.forElementClickable(MERCURY_NAV_ICON); driver.findElement(MERCURY_NAV_ICON).click(); } else { WebElement avatar = wait.forElementVisible(By.cssSelector(LOGGED_IN_USER_SELECTOR_OASIS)); String loggedInUserName = avatar.getAttribute("alt"); if (!loggedInUserName.equals(userName)) { throw new IllegalArgumentException( "Invalid user, expected " + userName + ", but found: " + loggedInUserName); } } } finally { restoreDefaultImplicitWait(); driver.switchTo().defaultContent(); } PageObjectLogging.log("verifyUserLoggedIn", "user " + userName + " logged in", true); }
Source:
public JettyConfig getJettyConfig() { if(jettyConfig != null) { return jettyConfig; } else { return new DefaultJettyConfig(); } }

Target:
public JettyConfig getJettyConfig() { return jettyConfig != null ? jettyConfig : new DefaultJettyConfig(); }
Source:
public void verifyAddMessages() { List<String> messagesToAdd = new ArrayList(); messagesToAdd.add(TEST_STRING_ONE); messagesToAdd.add(TEST_STRING_TWO); messagesToAdd.add(TEST_STRING_ONE); messagesToAdd.add(TEST_STRING_THREE); messagesToAdd.add(TEST_STRING_TWO); validationResult.addMessages(messagesToAdd); assertEquals("There should only be three lines", 3, validationResult.getMessages().size()); assertEquals("There should only be five lines", 5, messagesToAdd.size()); }

Target:
public void verifyAddMessages() { List<String> messagesToAdd = new ArrayList<String>(); messagesToAdd.add(TEST_STRING_ONE); messagesToAdd.add(TEST_STRING_TWO); messagesToAdd.add(TEST_STRING_ONE); messagesToAdd.add(TEST_STRING_THREE); messagesToAdd.add(TEST_STRING_THREE_UPPER_CASE); validationResult.addMessages(messagesToAdd); assertEquals("There should only be three lines", 3, validationResult.getMessages().size()); assertEquals("There should only be five lines", 5, messagesToAdd.size()); }
Source:
public void updateGapHeader(M gapHeader) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) throw new IOException("GapWriter is closed"); m_gapHeader = gapHeader; if (m_activeSegment != null) { finishWrite(m_activeSegment); m_activeSegment = null; } } }

Target:
public void updateGapHeader(M gapHeader) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) throw new IOException("updateGapHeader call on closed PBD " + m_nonce); m_gapHeader = gapHeader; if (m_activeSegment!= null) { finishActiveSegmentWrite(); } } }
Source:
private void initList() { presenter.initList(entityId); if (!NetworkUtils.isInternetConnectionEstablished(getContext())) { handleNoInternet(); } else presenter.initList(entityId); }

Target:
private void initList() { presenter.initList(entityId); if (!NetworkUtils.isInternetConnectionEstablished(getContext())) { handleNoInternet(); } else { presenter.initList(entityId); } }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_activity_invisible); mProgressBar = new ProgressBar(new ContextThemeWrapper(this, getFlowParams().themeId)); mProgressBar.setIndeterminate(true); mProgressBar.setVisibility(View.INVISIBLE); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; FrameLayout container = findViewById(R.id.invisible_frame); container.addView(mProgressBar, params); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_activity_invisible); mProgressBar = new MaterialProgressBar(new ContextThemeWrapper(this, getFlowParams().themeId)); mProgressBar.setIndeterminate(true); mProgressBar.setVisibility(View.GONE); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; FrameLayout container = findViewById(R.id.invisible_frame); container.addView(mProgressBar, params); }
Source:
private void addSizedFiles(Collection<File> files) { if (files == null || files.isEmpty()) { return; } long size = 0l; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; }

Target:
protected void addSizedFiles(Collection<File> files) { if (files == null || files.isEmpty()) { return; } long size = 0l; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; }
Source:
private Path toDatabaseDirectory( String databaseName ) { return Config.fromFile( configDir.resolve( "neo4j.conf" ) ) .withHome( homeDir ) .withConnectorsDisabled() .withSetting( DatabaseManagementSystemSettings.active_database, databaseName ) .build().get( database_path ).toPath(); }

Target:
private Path toDatabaseDirectory( String databaseName ) { return Config.fromFile( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ) ) .withHome( homeDir ) .withConnectorsDisabled() .withSetting( DatabaseManagementSystemSettings.active_database, databaseName ) .build().get( database_path ).toPath(); }
Source:
protected void recomputeDocumentTypes() { Map<String, DocumentTypeDescriptor> dtds = new LinkedHashMap<>(); for (DocumentTypeDescriptor dtd : allDocumentTypes) { String name = dtd.name; DocumentTypeDescriptor newDtd = dtd; if (dtd.append && dtds.containsKey(dtd.name)) { newDtd = mergeDocumentTypeDescriptors(dtd, dtds.get(name)); } dtds.put(name, newDtd); } documentTypes.clear(); documentTypesExtending.clear(); registerDocumentType(new DocumentTypeImpl(TypeConstants.DOCUMENT)); for (String name : dtds.keySet()) { LinkedHashSet<String> stack = new LinkedHashSet<>(); recomputeDocumentType(name, stack, dtds); } documentTypesForFacet.clear(); for (DocumentType docType : documentTypes.values()) { for (String facet : docType.getFacets()) { documentTypesForFacet.computeIfAbsent(facet, k -> new HashSet<>()).add(docType.getName()); } } specialDocumentTypes.clear(); Set<String> specials = allDocumentTypes.stream() .filter(d -> Boolean.TRUE.equals(d.excludeFromCopy)) .map(d -> d.name) .collect(Collectors.toSet()); specialDocumentTypes = documentTypes.values().stream().filter(d -> specials.contains(d.getName())).collect(Collectors.toMap(DocumentType::getName, d -> d)); }

Target:
protected void recomputeDocumentTypes() { Map<String, DocumentTypeDescriptor> dtds = new LinkedHashMap<>(); for (DocumentTypeDescriptor dtd : allDocumentTypes) { String name = dtd.name; DocumentTypeDescriptor newDtd = dtd; if (dtd.append && dtds.containsKey(dtd.name)) { newDtd = mergeDocumentTypeDescriptors(dtd, dtds.get(name)); } dtds.put(name, newDtd); } documentTypes.clear(); documentTypesExtending.clear(); registerDocumentType(new DocumentTypeImpl(TypeConstants.DOCUMENT)); for (String name : dtds.keySet()) { LinkedHashSet<String> stack = new LinkedHashSet<>(); recomputeDocumentType(name, stack, dtds); } documentTypesForFacet.clear(); for (DocumentType docType : documentTypes.values()) { for (String facet : docType.getFacets()) { documentTypesForFacet.computeIfAbsent(facet, k -> new HashSet<>()).add(docType.getName()); } } specialDocumentTypes = dtds.values().stream() .filter(d -> Boolean.TRUE.equals(d.special)) .map(d -> d.name) .collect(Collectors.toSet()); }
Source:
public static Expression convertToRoundExpressionIfNeeded(PDataType fromDataType, PDataType targetDataType, List<Expression> expressions) throws SQLException { Expression firstChildExpr = expressions.get(0); if(fromDataType == PDataType.DECIMAL && targetDataType.isCoercibleTo(PDataType.LONG)) { return new RoundDecimalExpression(expressions); } else if(fromDataType == PDataType.TIMESTAMP && targetDataType.isCoercibleTo(PDataType.DATE)) { Expression millisLiteral = LiteralExpression.newConstant(TimeUnit.MILLISECOND.name(), PDataType.VARCHAR); return new RoundTimestampExpression(Lists.newArrayList(expressions.get(0), millisLiteral)); } else if(!fromDataType.isCoercibleTo(targetDataType)) { throw new TypeMismatchException(fromDataType, targetDataType, firstChildExpr.toString()); } return firstChildExpr; }

Target:
public static Expression convertToRoundExpressionIfNeeded(PDataType fromDataType, PDataType targetDataType, List<Expression> expressions) throws SQLException { Expression firstChildExpr = expressions.get(0); if(fromDataType == targetDataType) { return firstChildExpr; } else if(fromDataType == PDataType.DECIMAL && targetDataType.isCoercibleTo(PDataType.LONG)) { return new RoundDecimalExpression(expressions); } else if(fromDataType == PDataType.TIMESTAMP && targetDataType.isCoercibleTo(PDataType.DATE)) { return RoundTimestampExpression.create(expressions.get(0)); } else if(!fromDataType.isCoercibleTo(targetDataType)) { throw new TypeMismatchException(fromDataType, targetDataType, firstChildExpr.toString()); } return firstChildExpr; }
Source:
public void setup() throws IOException { InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json"); try { byte[] data = toByteArray(input); mockClient = new MockClient(); github = Feign.builder().decoder(new AssertionDecoder(new GsonDecoder())) .client(mockClient.ok(HttpMethod.GET, "/repos/netflix/feign/contributors", data) .ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=55") .ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=7 7", new ByteArrayInputStream(data)) .ok(HttpMethod.POST, "/repos/netflix/feign/contributors", "{\"login\":\"velo\",\"contributions\":0}") .noContent(HttpMethod.PATCH, "/repos/velo/feign-mock/contributors") .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=1234567890", HttpsURLConnection.HTTP_NOT_FOUND) .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, new ByteArrayInputStream(data)) .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, "") .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, data)) .target(new MockTarget<GitHub>(GitHub.class)); } finally { input.close(); } }

Target:
public void setup() throws IOException { try (InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json")) { byte[] data = toByteArray(input); mockClient = new MockClient(); github = Feign.builder().decoder(new AssertionDecoder(new GsonDecoder())) .client(mockClient.ok(HttpMethod.GET, "/repos/netflix/feign/contributors", data) .ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=55") .ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=7 7", new ByteArrayInputStream(data)) .ok(HttpMethod.POST, "/repos/netflix/feign/contributors", "{\"login\":\"velo\",\"contributions\":0}") .noContent(HttpMethod.PATCH, "/repos/velo/feign-mock/contributors") .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=1234567890", HttpsURLConnection.HTTP_NOT_FOUND) .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, new ByteArrayInputStream(data)) .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, "") .add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, data)) .target(new MockTarget<>(GitHub.class)); } }
Source:
private void loadPlugIns() { Collection<File> plugInJars = Collections.emptyList(); try { plugInJars = getPluginFiles(); } catch (IOException e) { log.error("Cannot scan Gerrit plugins directory looking for jar files", e); return; } for (File jarFile : plugInJars) { Plugin plugIn; try { plugIn = loadPlugin(jarFile); pluginCache.put(plugIn.name, plugIn); } catch (IOException e) { log.warn("Cannot access PlugIn jar " + jarFile, e); } catch (ClassNotFoundException e) { log.warn("Cannot load PlugIn class module from " + jarFile, e); } } }

Target:
private void loadPlugIns() { Collection<File> plugInJars; try { plugInJars = getPluginFiles(); } catch (IOException e) { log.error("Cannot scan Gerrit plugins directory looking for jar files", e); return; } for (File jarFile : plugInJars) { Plugin plugIn; try { plugIn = loadPlugin(jarFile); pluginCache.put(plugIn.name, plugIn); } catch (IOException e) { log.warn("Cannot access PlugIn jar " + jarFile, e); } catch (ClassNotFoundException e) { log.warn("Cannot load PlugIn class module from " + jarFile, e); } } }
Source:
private void addAllMedia(List<Uri> mediaUris) { for (Uri mediaUri : mediaUris) { if (mediaUri == null) { Toast.makeText(EditPostActivity.this, getString(R.string.gallery_error), Toast.LENGTH_SHORT).show(); continue; } if (!addMedia(mediaUri)) { Toast.makeText(EditPostActivity.this, getResources().getText(R.string.gallery_error), Toast.LENGTH_SHORT).show(); } } }

Target:
private void addAllMedia(List<Uri> mediaUris) { boolean isErrorAddingMedia = false; for (Uri mediaUri : mediaUris) { if (mediaUri == null || !addMedia(mediaUri)) { isErrorAddingMedia = true; } } if (isErrorAddingMedia) { Toast.makeText(EditPostActivity.this, getResources().getText(R.string.gallery_error), Toast.LENGTH_SHORT).show(); } }
Source:
private void getNoteByRevisionForCompare(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String revisionId = (String) fromMessage.get("revisionId"); String position = (String) fromMessage.get("position"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Note revisionNote; if (revisionId.equals("Head")) { revisionNote = notebook.loadNoteFromRepo(noteId, subject); } else { revisionNote = notebook.getNoteByRevision(noteId, revisionId, subject); } conn.send(serializeMessage( new Message(OP.NOTE_REVISION_FOR_COMPARE).put("noteId", noteId) .put("revisionId", revisionId).put("position", position).put("note", revisionNote))); }

Target:
private void getNoteByRevisionForCompare(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String revisionId = (String) fromMessage.get("revisionId"); String position = (String) fromMessage.get("position"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Note revisionNote; if (revisionId.equals("Head")) { revisionNote = notebook.getNote(noteId); } else { revisionNote = notebook.getNoteByRevision(noteId, revisionId, subject); } conn.send(serializeMessage( new Message(OP.NOTE_REVISION_FOR_COMPARE).put("noteId", noteId) .put("revisionId", revisionId).put("position", position).put("note", revisionNote))); }
Source:
public EventHubClient build() { this.configuration = this.configuration == null ? ConfigurationManager.getConfiguration().clone() : this.configuration; this.proxyConfiguration = constructDefaultProxyConfiguration(this.configuration); if (this.credentials == null) { String connStr = this.configuration.get(AZURE_EVENT_HUB_CONNECTION_STRING); this.credentials = new CredentialInfo(connStr); } if (this.duration == null) { this.duration = Duration.ofSeconds(5); } if (this.scheduler == null) { this.scheduler = Schedulers.elastic(); } return new EventHubClient(); }

Target:
public EventHubClient build() { configuration = configuration == null ? ConfigurationManager.getConfiguration().clone() : configuration; if (credentials == null) { String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (ImplUtils.isNullOrEmpty(connectionString)) { throw new IllegalArgumentException("Connection string is null or empty."); } credentials = CredentialInfo.from(connectionString); } if (timeout == null) { timeout = Duration.ofSeconds(60); } final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final SharedAccessSignatureTokenProvider tokenProvider; try { tokenProvider = new SharedAccessSignatureTokenProvider(credentials.sharedAccessKeyName(), credentials.sharedAccessKey()); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AzureException("Could not create token provider."); } if (retry == null) { retry = Retry.getDefaultRetry(); } proxyConfiguration = constructDefaultProxyConfiguration(configuration); if (scheduler == null) { scheduler = Schedulers.elastic(); } ConnectionParameters connectionParameters = new ConnectionParameters(credentials, timeout, tokenProvider, transport, retry, proxyConfiguration, scheduler); return new EventHubClient(connectionParameters, tokenProvider, provider, handlerProvider, scheduler); }
Source:
public void setVisible(boolean visible) { if (visible) { if (!isPage2Visited) { this.modelName.setText(extractModelName(firstPage.getProjectName())); } isPage2Visited = visible; } super.setVisible(visible); }

Target:
public void setVisible(boolean visible) { if (visible) { if (!isVsmNameChanged) { this.modelName.setText(extractModelName(firstPage.getProjectName())); } } super.setVisible(visible); }
Source:
private String readJSONFile(File src) throws IOException { BufferedReader br = null; try { String line = null; StringBuilder builder = new StringBuilder(); br = new BufferedReader(new FileReader(src)); while ((line = br.readLine()) != null) { builder.append(line); } return builder.toString(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { Timber.e(ex, "Exception thrown while closing an input stream due to: %s ", ex.getMessage()); } } }

Target:
private String readJSONFile(File src) throws IOException { StringBuilder builder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(src))) { String line; while ((line = br.readLine()) != null) { builder.append(line); } return builder.toString(); } }
Source:
public void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); }

Target:
private void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); }
Source:
protected Boolean doInBackground(Void... params) { if (mEditPostRepository.postHasEdits()) { mEditPostRepository.updateInTransaction(postModel -> { updatePostContentNewEditor(postModel); return true; }); mViewModel.savePostToDb(EditPostActivity.this, mEditPostRepository, mShowAztecEditor); ENDING`. This happens in this scenario: ENDING` ENDING`, the Post List will indefinitely show a “Queued post” ENDING` for WPCom because the app will automatically mDispatcher.dispatch(UploadActionBuilder.newCancelPostAction(mEditPostRepository.getEditablePost())); PendingDraftsNotificationsUtils .scheduleNextNotifications(EditPostActivity.this, mEditPostRepository.getId(), mEditPostRepository.getDateLocallyChanged()); } return true; }

Target:
protected Boolean doInBackground(Void... params) { if (mEditPostRepository.postHasEdits()) { mEditPostRepository.updateInTransaction(postModel -> { updatePostLocallyChangedOnStatusOrMediaChange(postModel); return true; }); mViewModel.savePostToDb(EditPostActivity.this, mEditPostRepository, mShowAztecEditor); ENDING`. This happens in this scenario: ENDING` ENDING`, the Post List will indefinitely show a “Queued post” ENDING` for WPCom because the app will automatically mDispatcher.dispatch(UploadActionBuilder.newCancelPostAction(mEditPostRepository.getEditablePost())); PendingDraftsNotificationsUtils .scheduleNextNotifications(EditPostActivity.this, mEditPostRepository.getId(), mEditPostRepository.getDateLocallyChanged()); } return true; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { searchResultsFragment.startSearch(query, query != null && query.length() > 1); } } } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { startSearch(query, query != null && query.length() > 1); } } } }
Source:
public void testGeneratePartitions() { Set<Set<Integer>> partitions = generatePartitions(4); assertEquals(partitions, ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2), ImmutableSet.of(0, 3), ImmutableSet.of(0, 1, 2), ImmutableSet.of(0, 1, 3), ImmutableSet.of(0, 2, 3))); partitions = generatePartitions(3); assertEquals(partitions, ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2))); }

Target:
public void testGeneratePartitions() { assertEquals(generatePartitions(4), ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2), ImmutableSet.of(0, 3), ImmutableSet.of(0, 1, 2), ImmutableSet.of(0, 1, 3), ImmutableSet.of(0, 2, 3))); assertEquals(generatePartitions(3), ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2))); }
Source:
private void registerListener() { if (!PlatformUI.isWorkbenchRunning()) { return; } final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); IViewPart view = activePage.findView(CriticalPathView.ID); if (view != null) { if (activePage.isPartVisible(view)) { toggleActive(true); } } view = activePage.findView(ControlFlowView.ID); if (view != null) { view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(fSelListener); view.getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener); } }

Target:
private void registerListener() { if (!PlatformUI.isWorkbenchRunning()) { return; } IWorkbench wb = PlatformUI.getWorkbench(); if (wb == null) { return; } IWorkbenchWindow wbw = wb.getActiveWorkbenchWindow(); if (wbw == null) { return; } final IWorkbenchPage activePage = wbw.getActivePage(); if (activePage == null) { return; } IViewPart view = activePage.findView(CriticalPathView.ID); if (view != null) { if (activePage.isPartVisible(view)) { toggleActive(true); } } view = activePage.findView(ControlFlowView.ID); if (view != null) { view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(fSelListener); view.getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener); } }
Source:
public long getAbsSendTime(RawPacket pkt) { long absSendTime = -1L; HeaderExtension header = hasAbsoluteSendTimeExtension(pkt); if (header != null) { int offSet = header.getOffset() + 1; if (header.getExtLength() == EXT_LENGTH) { absSendTime = (header.getBuffer()[offSet] & 0xFF) << 16 | (header.getBuffer()[offSet + 1] & 0xFF) << 8 | (header.getBuffer()[offSet + 2] & 0xFF); } } return absSendTime; }

Target:
public long getAbsSendTime(RawPacket pkt) { long absSendTime = -1L; HeaderExtension header = getAbsoluteSendTimeExtension(pkt); if (header != null) { int offSet = header.getOffset() + 1; if (header.getExtLength() == EXT_LENGTH) { absSendTime = RTPUtils.readUint24AsInt(header.getBuffer(),offSet); } } return absSendTime; }
Source:
public String format(Date date, String... args) { if (date == null) { return null; } String format; if (args.length > 0) { format = args[0]; } else { format = DEFAULT_FORMAT; } SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(format); } catch (IllegalArgumentException e) { sdf = new SimpleDateFormat(DEFAULT_FORMAT); } return sdf.format(date); }

Target:
public String format( Date date, String... args ) { if( date == null ) { return ""; } if( args.length == 0 ) { throw new JGivenWrongUsageException( String.format( "A SimpleDateFormat pattern is expected as first argument" ) ); } String pattern = args[0]; Locale locale = Locale.getDefault(); if( args.length > 1 ) { locale = new Locale( args[1] ); } SimpleDateFormat sdf; try { sdf = new SimpleDateFormat( pattern, locale ); } catch( IllegalArgumentException e ) { throw new JGivenWrongUsageException( String.format( "A valid SimpleDateFormat pattern is expected (was '%s')", pattern ) ); } return sdf.format( date ); }
Source:
public void executeBatch(OperationsQueue operationsQueue) { log.tracef( "Executing batch" ); try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }

Target:
public void executeBatch(OperationsQueue operationsQueue) { try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { log.tracef( "Executing batch" ); super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }
Source:
public static boolean waitFor(File file, int timeout) { long stopAt = System.currentTimeMillis() + timeout; while (!file.exists()) { if (System.currentTimeMillis() > stopAt) { return false; } try { Thread.sleep(100); } catch (InterruptedException ignore) { } catch (Exception ex) { break; } } return true; }

Target:
public static boolean waitFor(File file, int timeout) { long stopAt = System.currentTimeMillis() + timeout; while (!file.exists()) { if (System.currentTimeMillis() > stopAt) { return false; } try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception ex) { break; } } return true; }
Source:
public Optional<TableReference> chooseNextTableToSweep(Transaction tx, long conservativeSweepTs) { if (hasRemappedStreamStoreValueTable) { Preconditions.checkState(previousStreamStoreValueTable != null, "we should have set previousStreamStoreValueTable on the previous iteration"); hasRemappedStreamStoreValueTable = false; return Optional.of(previousStreamStoreValueTable); } Optional<TableReference> tableReferenceOptional = delegate.chooseNextTableToSweep(tx, conservativeSweepTs); if (!tableReferenceOptional.isPresent()) { return tableReferenceOptional; } TableReference tableReference = tableReferenceOptional.get(); if (!StreamTableType.isStreamStoreValueTable(tableReference)) { return Optional.of(tableReference); } previousStreamStoreValueTable = tableReference; hasRemappedStreamStoreValueTable = true; return Optional.of(StreamTableType.getIndexFromValue(tableReference)); }

Target:
public Optional<TableReference> chooseNextTableToSweep(Transaction tx, long conservativeSweepTs) { if (hasRemappedStreamStoreValueTable) { hasRemappedStreamStoreValueTable = false; return Optional.of(previousStreamStoreValueTable); } Optional<TableReference> tableReferenceOptional = delegate.chooseNextTableToSweep(tx, conservativeSweepTs); if (!tableReferenceOptional.isPresent()) { return tableReferenceOptional; } TableReference tableReference = tableReferenceOptional.get(); if (!StreamTableType.isStreamStoreValueTable(tableReference)) { return Optional.of(tableReference); } previousStreamStoreValueTable = tableReference; hasRemappedStreamStoreValueTable = true; return Optional.of(StreamTableType.getIndexTableFromValueTable(tableReference)); }
Source:
public Repository getRepository() { return(repo); }

Target:
public Repository getRepository() { return repo; }
Source:
protected void obtainResource() throws Exception { this.zkClient = new ZkClient(zkConnectString, 5000, 5000, new ZkStringSerializer()); if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available on localhost"); }; }

Target:
protected void obtainResource() throws Exception { try { this.zkClient = new ZkClient(zkConnectString, 5000, 5000, ZKStringSerializer$.MODULE$); if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available on localhost"); } } catch (Exception e) { throw new RuntimeException("Issues connecting to ZK server"); } }
Source:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final MomPolicyUpdateParams policyParams) { if (policyParams == null || policyParams.cluster == null || policyParams.allHostsInCluster == null) return; List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : policyParams.allHostsInCluster) { if (vds.getStatus() == VDSStatus.Up) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { return runUpdateMomPolicy(policyParams.cluster, vds); } }); } } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }

Target:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final MomPolicyUpdateParams policyParams) { if (policyParams == null || policyParams.cluster == null || policyParams.allHostsInCluster == null) return; List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : policyParams.allHostsInCluster) { if (vds.getStatus() == VDSStatus.Up) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { VDSReturnValue returnValue = new VDSReturnValue(); if (policyParams.cluster.getCompatibilityVersion().compareTo(Version.v3_4) >= 0) { try { returnValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, policyParams.cluster.isEnableBallooning(), policyParams.cluster.isEnableKsm(), policyParams.cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); returnValue.setSucceeded(false); } } return returnValue; } }); } } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }
Source:
private Map<String, Map<String, Map<String, String>>> getToolFromQuay(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = QUAY_URL + "repository/" + repo; final Optional<String> asStringBuilds = ResourceUtilities.asString(repoUrl, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { final String json = asStringBuilds.get(); Gson gson = new Gson(); Map<String, Map<String, Map<String, String>>> map = new HashMap<>(); map = (Map<String, Map<String, Map<String, String>>>)gson.fromJson(json, map.getClass()); return map; } return null; }

Target:
private Optional<Map<String, Map<String, Map<String, String>>>> getToolFromQuay(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = QUAY_URL + "repository/" + repo; final Optional<String> asStringBuilds = ResourceUtilities.asString(repoUrl, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { final String json = asStringBuilds.get(); Gson gson = new Gson(); Map<String, Map<String, Map<String, String>>> map = new HashMap<>(); map = (Map<String, Map<String, Map<String, String>>>)gson.fromJson(json, map.getClass()); return Optional.of(map); } return Optional.empty(); }
Source:
private static URI createURI(List<Integer> proxyPorts) { Optional<String> reduce = proxyPorts.stream() .map(port -> "localhost:" + port) .reduce((x1, x2) -> x1 + STRIPE_SEPARATOR + x2); String uri = "terracotta://" + reduce.get(); return URI.create(uri); }

Target:
private static URI createURI(List<Integer> proxyPorts) { String uri = proxyPorts.stream() .map(port -> "localhost:" + port) .collect(Collectors.joining(",", "terracotta://", "")); return URI.create(uri); }
Source:
void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> { tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume(); return null; }); } VersionedThingWithAssignedId thing = repository.findById(1L).get(); repository.delete(thing); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }

Target:
void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume()); } VersionedThingWithAssignedId thing = repository.findById(1L).get(); repository.delete(thing); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }
Source:
private AuthenticationException onError(JwtException e) { if (logger.isDebugEnabled()) { logger.debug("Authentication error for Jwt Token: " + e.getMessage()); } if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }

Target:
private AuthenticationException onError(JwtException e) { if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }
Source:
public void testInitializationTimestampForwardedToExecutionGraph() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); CommonTestUtils.waitUntilCondition(() -> dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT).get() == JobStatus.RUNNING, Deadline.fromNow(Duration.of(10, ChronoUnit.SECONDS)), 5L); ArchivedExecutionGraph result = dispatcher.requestJob(jobGraph.getJobID(), TIMEOUT).get(); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.CREATED), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.RUNNING), greaterThan(0L)); }

Target:
public void testInitializationTimestampForwardedToExecutionGraph() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); CommonTestUtils.waitUntilCondition( () -> dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT).get() == JobStatus.RUNNING, Deadline.fromNow(Duration.ofSeconds(10)), 5L); ArchivedExecutionGraph result = dispatcher.requestJob(jobGraph.getJobID(), TIMEOUT).get(); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.CREATED), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.RUNNING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING) <= result.getStatusTimestamp(JobStatus.CREATED), is(true)); }
Source:
private static TypedResource extractTypedItems(XpathResourceXmlLoader.XmlNode xmlNode, ResType arrayResType, XmlLoader.XmlContext xmlContext) { final List<TypedResource> items = new ArrayList<>(); for (XpathResourceXmlLoader.XmlNode item : xmlNode.selectElements("item")) { final String itemString = item.getTextContent(); ResType itemResType = null; if (Pattern.matches("\\d+", itemString)) { itemResType = ResType.INTEGER; } else if (itemString.charAt(0) == '#') { itemResType = ResType.COLOR; } else if (itemString.contains("px") || itemString.contains("sp") || itemString.contains("dp")) { itemResType = ResType.DIMEN; } else if (Pattern.matches("\\d+.+?", itemString)) { itemResType = ResType.FLOAT; } else if (itemString.equals("true") || itemString.equals("false")) { itemResType = ResType.BOOLEAN; } else if (!(itemString.charAt(0) == '@' && itemString.contains("/"))) { itemResType = ResType.CHAR_SEQUENCE; } items.add(new TypedResource<>(itemString, itemResType, xmlContext)); } final TypedResource[] typedResources = items.toArray(new TypedResource[items.size()]); return new TypedResource<>(typedResources, arrayResType, xmlContext); }

Target:
private static TypedResource extractTypedItems(XpathResourceXmlLoader.XmlNode xmlNode, ResType arrayResType, XmlLoader.XmlContext xmlContext) { final List<TypedResource> items = new ArrayList<>(); for (XpathResourceXmlLoader.XmlNode item : xmlNode.selectElements("item")) { final String itemString = item.getTextContent(); ResType itemResType = inferFromValue(itemString); if (itemResType == ResType.CHAR_SEQUENCE) { if (ResourceValue.isStyleReference(itemString)) { itemResType = ResType.STYLE; } else if (itemString.equals("@null")) { itemResType = ResType.NULL; } else if (ResourceValue.isResourceReference(itemString)) { itemResType = null; } } items.add(new TypedResource<>(itemString, itemResType, xmlContext)); } final TypedResource[] typedResources = items.toArray(new TypedResource[items.size()]); return new TypedResource<>(typedResources, arrayResType, xmlContext); }
Source:
public void onMyLocationChange(@Nullable Location location) { WritableMap event = Arguments.createMap(); WritableMap src = Arguments.createMap(); if (location == null) { src.putString("message", "Could not get user location"); event.putMap("src", src); emitEvent("onLocateUserFailed", event); return; } src.putDouble("latitude", location.getLatitude()); src.putDouble("longitude", location.getLongitude()); src.putDouble("magneticHeading", location.getBearing()); src.putDouble("trueHeading", location.getBearing()); src.putDouble("headingAccuracy", 10.0); src.putBoolean("isUpdating", true); event.putMap("src", src); emitEvent("onUpdateUserLocation", event); }

Target:
public void onMyLocationChange(@Nullable Location location) { WritableMap event = Arguments.createMap(); WritableMap src = Arguments.createMap(); if (location == null) { src.putString("message", "Could not get user location"); event.putMap("src", src); emitEvent("onLocateUserFailed", event); return; } src.putDouble("latitude", location.getLatitude()); src.putDouble("longitude", location.getLongitude()); if (location.hasAccuracy()) { src.putDouble("verticalAccuracy", location.getAccuracy()); src.putDouble("horizontalAccuracy", location.getAccuracy()); } GeomagneticField geoField = new GeomagneticField( (float)location.getLatitude(), (float)location.getLongitude(), location.hasAltitude() ? (float)location.getAltitude() : 0.0f, System.currentTimeMillis() ); src.putDouble("magneticHeading", location.getBearing()); src.putDouble("trueHeading", location.getBearing() + geoField.getDeclination()); event.putMap("src", src); emitEvent("onUpdateUserLocation", event); }