auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>PhoneNumberSearch> beginPurchaseSearch(String searchId, Duration pollInterval) { Objects.requireNonNull(searchId, "'searchId' can not be null."); if (pollInterval == null) { <START> pollInterval = Duration.ofSeconds(5); <END> } return new PollerFlux<PhoneNumberSearch, PhoneNumberSearch>(pollInterval, purchaseSearchActivationOperation(searchId), purchaseSearchPollOperation(searchId), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported")), purchaseSearchFetchResultOperation()); }</code><technical_language>a const (DEFAULT_POLL_INTERVAL) reuse in other methods well? I guess other operation right is beginCreateSearch add beginReleasePhoneNumber, default for</technical_language>

Target:
public PollerFlux<Void, Void> beginPurchaseSearch(String searchId, Duration pollInterval) { Objects.requireNonNull(searchId, "'searchId' can not be null."); if (pollInterval == null) { pollInterval = defaultPollInterval; } return new PollerFlux<Void, Void>(pollInterval, purchaseSearchActivationOperation(searchId), purchaseSearchPollOperation(searchId), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported")), purchaseSearchFetchResultOperation()); }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { TracingTags.WORKSPACE_ID.set(identity::getWorkspaceId); <START> List<SshPairImpl> vcsSshPairs = getVcsSshPairs(identity); <END> List<SshPairImpl> systemSshPairs = getSystemSshPairs(identity); List<SshPairImpl> all = new ArrayList<>(vcsSshPairs); all.addAll(systemSshPairs); doProvisionSshKeys(all, k8sEnv, identity.getWorkspaceId()); StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } String sshConfigMapName = identity.getWorkspaceId() + SSH_CONFIG_MAP_NAME_SUFFIX; doProvisionSshConfig(sshConfigMapName, sshConfigData.toString(), k8sEnv); }</code><technical_language>I propose rewrite in suggestion List<SshPairImpl> vcsSshPairs = getVcsSshPairs(identity); List<SshPairImpl> systemSshPairs = getSystemSshPairs(identity); List<SshPairImpl> = new ArrayList<>(vcsSshPairs); all.addAll(systemSshPairs); doProvisionSshKeys(all, k8sEnv, identity.getWorkspaceId()); doProvisionVcsSshConfig(vcsSshPairs, k8sEnv); } ... doProvisionVcsSshConfig(... { StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } String sshConfigMapName = identity.getWorkspaceId() + SSH_CONFIG_MAP_NAME_SUFFIX; ... }</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { String workspaceId = identity.getWorkspaceId(); TracingTags.WORKSPACE_ID.set(workspaceId); List<SshPairImpl> vcsSshPairs = getVcsSshPairs(k8sEnv, identity); List<SshPairImpl> systemSshPairs = getSystemSshPairs(k8sEnv, identity); List<SshPairImpl> all = new ArrayList<>(vcsSshPairs); all.addAll(systemSshPairs); doProvisionSshKeys(all, k8sEnv, workspaceId); doProvisionVcsSshConfig(vcsSshPairs, k8sEnv, workspaceId); }
Source:
<code>public Parser<String, Object> makeParser() { <START> if(flattenSpec.isEnabled()) { <END> return new JSONPathParser(convertFieldSpecs(flattenSpec.getFields()), flattenSpec.usingFieldDiscovery()); } else { return new JSONParser(objectMapper, null); } }</code><technical_language>this flattenSpec != null ? passed flattenSpec through</technical_language>

Target:
public Parser<String, Object> makeParser() { return new JSONPathParser( convertFieldSpecs(flattenSpec.getFields()), flattenSpec.isUseFieldDiscovery(), objectMapper ); }
Source:
<code>private Set<String> getDefaultOrigins() { List<VDS> allVds = vdsDao.getAll(getUserID(), getParameters().isFiltered()); <START> Set<String> result = new HashSet<>(); <END> for (VDS vds : allVds) { if (!getParameters().getSuffixes().isEmpty()) { for (String suffix : getParameters().getSuffixes()) { result.add(HTTPS + vds.getHostName() + suffix); } } else { result.add(HTTPS + vds.getHostName()); } } if (log.isDebugEnabled()) { log.debug("Default list of origins refreshed to: {}", StringUtils.join(result, ',')); } return result; }</code><technical_language>please a more meaningful name. allowedOrigins</technical_language>

Target:
private Set<String> getDefaultOrigins() { List<VDS> allVds = vdsDao.getAll(getUserID(), getParameters().isFiltered()); Set<String> allowedOrigins = new HashSet<>(); if (getParameters().getSuffixes().isEmpty()) { allVds.stream().forEach( vds -> allowedOrigins.add(String.format("https://%s", vds.getHostName()))); } else { allVds.stream().forEach( vds -> allowedOrigins.addAll(getHostOrigins(vds.getHostName(), getParameters().getSuffixes()))); } if (log.isDebugEnabled()) { log.debug("Default list of origins refreshed to: {}", StringUtils.join(allowedOrigins, ',')); } return allowedOrigins; }
Source:
<code>public boolean isValid(ILaunchConfiguration config) { <START> if (!super.isValid(config)) <END> return false; setErrorMessage(null); int currentSelection = connectionCombo.getSelectionIndex(); if (currentSelection < 0) { setErrorMessage(CONNECTION_TEXT_ERROR); return false; } String connection_name = connectionCombo.getItem(currentSelection); if (connection_name.isEmpty()) { setErrorMessage(CONNECTION_TEXT_ERROR); return false; } String remoteProgName = remoteProgText.getText().trim(); if (remoteProgName.isEmpty()) { setErrorMessage(REMOTE_PROG_TEXT_ERROR); return false; } Path remoteProgPath = Path.forPosix(remoteProgName); if (!remoteProgPath.isAbsolute()) { setErrorMessage(REMOTE_PROG_NOT_ABSOLUTE); return false; } return true; }</code><technical_language>for Sonar stats brackets, if "if" block contains a single instruction</technical_language>

Target:
public boolean isValid(ILaunchConfiguration config) { if (!super.isValid(config)) { return false; } setErrorMessage(null); int currentSelection = connectionCombo.getSelectionIndex(); if (currentSelection < 0) { setErrorMessage(CONNECTION_TEXT_ERROR); return false; } String connection_name = connectionCombo.getItem(currentSelection); if (connection_name.isEmpty()) { setErrorMessage(CONNECTION_TEXT_ERROR); return false; } String remoteProgName = remoteProgText.getText().trim(); if (remoteProgName.isEmpty()) { setErrorMessage(REMOTE_PROG_TEXT_ERROR); return false; } Path remoteProgPath = Path.forPosix(remoteProgName); if (!remoteProgPath.isAbsolute()) { setErrorMessage(REMOTE_PROG_NOT_ABSOLUTE); return false; } return true; }
Source:
<code>public void process() throws IOException, ClientConnectionException { processIncoming(); <START> checkHeartBeat(); <END> processOutgoing(); }</code><technical_language>call processHeartbeat, more a check</technical_language>

Target:
public void process() throws IOException, ClientConnectionException { processIncoming(); processHeartbeat(); processOutgoing(); }
Source:
<code>protected SparseHtmlFile getSparseHtmlFileB(PatchScript s) { AccountDiffPreference dp = new AccountDiffPreference(s.getDiffPrefs()); PrettyFormatter f = ClientSideFormatter.FACTORY.get(); f.setDiffPrefs(dp); f.setFileName(s.getB().getPath()); f.setEditFilter(PrettyFormatter.B); f.setEditList(s.getEdits()); <START> if ((dp.isSyntaxHighlighting() || dp.getContext() != AccountDiffPreference.WHOLE_FILE_CONTEXT) <END> && s.getA().isWholeFile() && !s.getB().isWholeFile()) { f.format(s.getB().apply(s.getA(), s.getEdits())); } else { f.format(s.getB()); } return f; }</code><technical_language>I this is right phrase it. I rewriting expression build full side of B if A isWholeFile B !isWholeFile. This is requirement needed correctly expand</technical_language>

Target:
protected SparseHtmlFile getSparseHtmlFileB(PatchScript s) { AccountDiffPreference dp = new AccountDiffPreference(s.getDiffPrefs()); SparseFileContent b = s.getB(); PrettyFormatter f = ClientSideFormatter.FACTORY.get(); f.setDiffPrefs(dp); f.setFileName(b.getPath()); f.setEditFilter(PrettyFormatter.B); f.setEditList(s.getEdits()); if (s.getA().isWholeFile() && !b.isWholeFile()) { b = b.apply(s.getA(), s.getEdits()); } f.format(b); return f; }
Source:
<code>public URI getProcessDataDirectory(Process process) { if (Objects.isNull(process.getProcessBaseUri())) { process.setProcessBaseUri(fileService.getProcessBaseUriForExistingProcess(process)); <START> if (!isUnitTesting) { <END> try { save(process); } catch (DataException e) { logger.error(e.getMessage(), e); return URI.create(""); } } } return process.getProcessBaseUri(); }</code><technical_language>saving in test</technical_language>

Target:
public URI getProcessDataDirectory(Process process) { if (Objects.isNull(process.getProcessBaseUri())) { process.setProcessBaseUri(fileService.getProcessBaseUriForExistingProcess(process)); try { save(process); } catch (DataException e) { logger.error(e.getMessage(), e); return URI.create(""); } } return process.getProcessBaseUri(); }
Source:
<code>void fullRefresh(boolean includeGraphs, boolean includeResults, boolean includeSourceFiles, boolean includeApplicationValues) { try { HPCCWsWorkUnitsClient wsWorkunitsClient = platform.getWsClient().getWsWorkunitsClient(); try { WorkunitWrapper wi = wsWorkunitsClient.getWUInfo(info.getWuid(), includeResults, includeGraphs, includeSourceFiles, includeApplicationValues, false, false, false, false, false); if (wi != null) { update(wi.getEclWorkunit()); if (wi.getResultViews() != null) { resultViews = Arrays.asList(wi.getResultViews()); } } } catch (Exception ex) { if (ex.getCause() != null) { Throwable cause = ex.getCause(); System.out.println(cause.getLocalizedMessage()); { setChanged(); notifyObservers(Notification.WORKUNIT); } } } catch (ArrayOfEspExceptionWrapper e) { <START> System.out.println(e.toString()); <END> } } catch (RemoteException e) { e.printStackTrace(); } catch (Exception e1) { e1.printStackTrace(); } }</code><technical_language>this log4j</technical_language>

Target:
void fullRefresh(boolean includeGraphs, boolean includeResults, boolean includeSourceFiles, boolean includeApplicationValues) { try { HPCCWsWorkUnitsClient wsWorkunitsClient = platform.getWsClient().getWsWorkunitsClient(); try { WorkunitWrapper wi = wsWorkunitsClient.getWUInfo(info.getWuid(), includeResults, includeGraphs, includeSourceFiles, includeApplicationValues, false, false, false, false, false); if (wi != null) { update(wi.getEclWorkunit()); if (wi.getResultViews() != null) { resultViews = Arrays.asList(wi.getResultViews()); } } } catch (Exception | ArrayOfEspExceptionWrapper ex) { if (ex.getCause() != null) { Throwable cause = ex.getCause(); System.out.println(cause.getLocalizedMessage()); { setChanged(); notifyObservers(Notification.WORKUNIT); } } } } catch (RemoteException e) { e.printStackTrace(); } catch (Exception e1) { e1.printStackTrace(); } }
Source:
<code>public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerAsyncClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(getReplayableBufferData(FORM_LOCAL_URL), <START> trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, null, <END> true, null).getSyncPoller(); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); }</code><technical_language>updatethese public API's in tests package private APIs. Applies test methods</technical_language>

Target:
public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerAsyncClient(httpClient, serviceVersion); customFormDataRunner((data, dataLength) -> beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = getFormTrainingAsyncClient(httpClient, serviceVersion).beginTraining(trainingFilesUrl, useTrainingLabels, null, durationTestMode).getSyncPoller(); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms( new RecognizeCustomFormsOptions(getReplayableBufferData(FORM_LOCAL_URL), dataLength, trainingPoller.getFinalResult().getModelId()) .setIncludeTextContent(true).setPollInterval(durationTestMode)).getSyncPoller(); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); }
Source:
<code>public CacheSimpleConfig(CacheSimpleConfig cacheSimpleConfig) { this.name = cacheSimpleConfig.name; this.keyType = cacheSimpleConfig.keyType; this.valueType = cacheSimpleConfig.valueType; this.statisticsEnabled = cacheSimpleConfig.statisticsEnabled; this.managementEnabled = cacheSimpleConfig.managementEnabled; this.readThrough = cacheSimpleConfig.readThrough; this.writeThrough = cacheSimpleConfig.writeThrough; this.cacheLoaderFactory = cacheSimpleConfig.cacheLoaderFactory; this.cacheWriterFactory = cacheSimpleConfig.cacheWriterFactory; this.expiryPolicyFactoryConfig = cacheSimpleConfig.expiryPolicyFactoryConfig; this.cacheEntryListeners = cacheSimpleConfig.cacheEntryListeners; this.asyncBackupCount = cacheSimpleConfig.asyncBackupCount; this.backupCount = cacheSimpleConfig.backupCount; this.inMemoryFormat = cacheSimpleConfig.inMemoryFormat; if (cacheSimpleConfig.evictionConfig != null) { this.evictionConfig = cacheSimpleConfig.evictionConfig; } this.wanReplicationRef = cacheSimpleConfig.wanReplicationRef; this.partitionLostListenerConfigs = new ArrayList<>(cacheSimpleConfig.getPartitionLostListenerConfigs()); this.quorumName = cacheSimpleConfig.quorumName; <START> this.mergePolicyConfig = cacheSimpleConfig.mergePolicyConfig; <END> this.hotRestartConfig = new HotRestartConfig(cacheSimpleConfig.hotRestartConfig); this.eventJournalConfig = new EventJournalConfig(cacheSimpleConfig.eventJournalConfig); this.disablePerEntryInvalidationEvents = cacheSimpleConfig.disablePerEntryInvalidationEvents; }</code><technical_language>a copy constructor</technical_language>

Target:
public CacheSimpleConfig(CacheSimpleConfig cacheSimpleConfig) { this.name = cacheSimpleConfig.name; this.keyType = cacheSimpleConfig.keyType; this.valueType = cacheSimpleConfig.valueType; this.statisticsEnabled = cacheSimpleConfig.statisticsEnabled; this.managementEnabled = cacheSimpleConfig.managementEnabled; this.readThrough = cacheSimpleConfig.readThrough; this.writeThrough = cacheSimpleConfig.writeThrough; this.cacheLoaderFactory = cacheSimpleConfig.cacheLoaderFactory; this.cacheWriterFactory = cacheSimpleConfig.cacheWriterFactory; this.expiryPolicyFactoryConfig = cacheSimpleConfig.expiryPolicyFactoryConfig; this.cacheEntryListeners = cacheSimpleConfig.cacheEntryListeners; this.asyncBackupCount = cacheSimpleConfig.asyncBackupCount; this.backupCount = cacheSimpleConfig.backupCount; this.inMemoryFormat = cacheSimpleConfig.inMemoryFormat; if (cacheSimpleConfig.evictionConfig != null) { this.evictionConfig = cacheSimpleConfig.evictionConfig; } this.wanReplicationRef = cacheSimpleConfig.wanReplicationRef; this.partitionLostListenerConfigs = new ArrayList<>(cacheSimpleConfig.getPartitionLostListenerConfigs()); this.quorumName = cacheSimpleConfig.quorumName; this.mergePolicyConfig = new MergePolicyConfig(cacheSimpleConfig.mergePolicyConfig); this.hotRestartConfig = new HotRestartConfig(cacheSimpleConfig.hotRestartConfig); this.eventJournalConfig = new EventJournalConfig(cacheSimpleConfig.eventJournalConfig); this.disablePerEntryInvalidationEvents = cacheSimpleConfig.disablePerEntryInvalidationEvents; }
Source:
<code>public void bind(Editing editingModel) { this.editingModel = editingModel; <START> LOG.info("Calling bind in ConfigurationViewModels"); <END> setAsObservableConfigModel(editingModel.currentConfig()); }</code><technical_language>delete</technical_language>

Target:
public void bind(Editing editingModel) { this.editingModel = editingModel; setAsObservableConfigModel(editingModel.currentConfig()); }
Source:
<code>public void testSyncInOnlyException() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"request\")}")) .throwException(new IllegalArgumentException("Illegal contennt!")) .to("mock:result"); } }; context.addRoutes(builder); try { <START> ServiceRegistry.get().register("GlobalCamelService", context); <END> String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("camel-endpoint-id", "start"); workItem.setParameter("request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); WorkItemHandler handler = new InOnlyCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(0)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }</code><technical_language>here, constant</technical_language>

Target:
public void testSyncInOnlyException() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"Request\")}")) .throwException(new IllegalArgumentException("Illegal contennt!")) .to("mock:result"); } }; context.addRoutes(builder); try { ServiceRegistry.get().register(JBPMConstants.GLOBAL_CAMEL_CONTEXT_SERVICE_KEY, context); String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM, "start"); workItem.setParameter("Request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); WorkItemHandler handler = new InOnlyCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(0)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }
Source:
<code>private void addSessionTrackingShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { <START> sessionTracker.setShuttingDown(true); <END> sessionExecutorService.shutdown(); try { if (!sessionExecutorService .awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS)) { LOGGER.warn("Shutdown of 'session tracking' threads" + " took too long - forcing a shutdown"); sessionExecutorService.shutdownNow(); } } catch (InterruptedException ex) { LOGGER.warn("Shutdown of 'session tracking' thread " + "was interrupted - forcing a shutdown"); sessionExecutorService.shutdownNow(); } } }); }</code><technical_language>this try flush session counts application shuts down</technical_language>

Target:
private void addSessionTrackingShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { sessionTracker.shutdown(); sessionExecutorService.shutdown(); try { if (!sessionExecutorService .awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { LOGGER.warn("Shutdown of 'session tracking' threads" + " took too long - forcing a shutdown"); sessionExecutorService.shutdownNow(); } } catch (InterruptedException ex) { LOGGER.warn("Shutdown of 'session tracking' thread " + "was interrupted - forcing a shutdown"); sessionExecutorService.shutdownNow(); } } }); }
Source:
<code>private String getSavedDvsSpawnedByRecurringDvForCurrentAndPastFiscalPeriodsSelectSql(Date currentFisalPeriodEndDate) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy", Locale.US); <START> return new String("SELECT B.DV_DOC_NBR, B.DV_CHECK_DT FROM KFS.FP_DV_DOC_T A, KFS.FP_RCDV_DTL_T B, CYNERGY.KREW_DOC_HDR_T C WHERE A.FDOC_NBR = B.DV_DOC_NBR AND C.DOC_HDR_ID = B.DV_DOC_NBR AND C.DOC_HDR_STAT_CD = '") +KewApiConstants.ROUTE_HEADER_SAVED_CD+ ("' AND B.DV_CHECK_DT <= '" +formatter.format(currentFisalPeriodEndDate)+ "'"); <END> }</code><technical_language>this line needs formatting</technical_language>

Target:
private String getSavedDvsSpawnedByRecurringDvForCurrentAndPastFiscalPeriodsSelectSql(Date currentFisalPeriodEndDate) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy", Locale.US); StringBuilder sqlBuilder = new StringBuilder("SELECT B.DV_DOC_NBR, B.DV_CHECK_DT "); sqlBuilder.append("FROM KFS.FP_DV_DOC_T A, KFS.FP_RCDV_DTL_T B, CYNERGY.KREW_DOC_HDR_T C "); sqlBuilder.append("WHERE A.FDOC_NBR = B.DV_DOC_NBR AND C.DOC_HDR_ID = B.DV_DOC_NBR "); sqlBuilder.append("AND C.DOC_HDR_STAT_CD = '").append(KewApiConstants.ROUTE_HEADER_SAVED_CD).append("' "); sqlBuilder.append("AND B.DV_CHECK_DT <= '").append(formatter.format(currentFisalPeriodEndDate)).append("'"); return sqlBuilder.toString(); }
Source:
<code>public static IProject getProject() { <START> CheatSheetView view = ViewUtilities.showCheatSheetView(); <END> if (view != null && view.getContent() != null) { String href = view.getContent().getHref(); if (href != null) { try { URL url = new URL(href); File file = null; if (ProjectExampleUtil.PROTOCOL_FILE.equals(url.getProtocol())) { try { file = new File(new URI(url.toExternalForm())); } catch (Exception e) { file = new File(url.getFile()); } } if (file != null && file.exists()) { IWorkspace workspace= ResourcesPlugin.getWorkspace(); IPath location= Path.fromOSString(file.getAbsolutePath()); if (location != null) { IFile iFile= workspace.getRoot().getFileForLocation(location); if (iFile != null) { return iFile.getProject(); } } } } catch (MalformedURLException e) { Activator.log(e); } } } return null; }</code><technical_language>this trigger view top ? in for a background utility method</technical_language>

Target:
public static IProject getProject() { CheatSheetView view = ViewUtilities.showCheatSheetView(); if (view != null && view.getContent() != null) { String href = view.getContent().getHref(); if (href != null) { try { URL url = new URL(href); File file = null; if (ProjectExampleUtil.PROTOCOL_FILE.equals(url.getProtocol())) { try { file = new File(new URI(url.toExternalForm())); } catch (Exception e) { file = new File(url.getFile()); } } return getProject(file); } catch (MalformedURLException e) { Activator.log(e); } } } IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page != null) { IEditorPart activeEditor = page.getActiveEditor(); if (activeEditor instanceof SimpleCSEditor || activeEditor instanceof CompCSEditor) { IEditorInput input = activeEditor.getEditorInput(); if (input instanceof IFileEditorInput) { IFile file = ((IFileEditorInput)input).getFile(); if (file != null && file.exists()) { return file.getProject(); } } } } return null; }
Source:
<code>public File get(final String bsn, final Version version, Map<String,String> properties, final DownloadListener... listeners) throws Exception { if (!inited) { init(); } final Entry<IMavenProjectFacade,MavenProject> entry = bsnMap.get(bsn); if (entry == null) return null; final MavenProject mavenProject = entry.getValue(); final String projectName = entry.getKey().getProject().getName(); properties.put("sourceProjectName", projectName); final File bundleFile = new File(mavenProject.getBuild().getDirectory(), mavenProject.getBuild().getFinalName() + ".jar"); if (listeners == null || listeners.length == 0) { <START> return bundleFile; <END> } new Job(getName() + " getting " + bsn) { @Override public IStatus run(IProgressMonitor monitor) { String failureReason = null; if (!bundleFile.exists()) { try { MavenUtil.execJarMojo(mavenProject, monitor); } catch (CoreException e) { failureReason = e.getMessage(); } } if (bundleFile.exists() && failureReason == null) { try { Domain domain = Domain.domain(bundleFile); String bundleBsn = domain.getBundleSymbolicName().getKey(); Version bundleVersion = new Version(domain.getBundleVersion()); if (!bsn.equals(bundleBsn)) { failureReason = "Bundle built by maven changed bsn"; } if (version.compareTo(bundleVersion) != 0) { failureReason = "Bundle built by maven changed version"; } } catch (IOException e) { failureReason = e.getMessage(); } } else { failureReason = "Maven build did not create bundle file"; } for (DownloadListener listener : listeners) { try { if (failureReason == null) { listener.success(bundleFile); } else { listener.failure(bundleFile, failureReason); } } catch (Throwable t) { logger.logError("Download listener error", t); } } return Status.OK_STATUS; } }.schedule(); return bundleFile; }</code><technical_language>return bundlefile here. need run java mojo it</technical_language>

Target:
public File get(final String bsn, final Version version, Map<String,String> properties, final DownloadListener... listeners) throws Exception { if (!inited) { init(); } final Entry<IMavenProjectFacade,MavenProject> entry = bsnMap.get(bsn); if (entry == null) return null; final MavenProject mavenProject = entry.getValue(); final String projectName = entry.getKey().getProject().getName(); properties.put("sourceProjectName", projectName); final File bundleFile = getBundleFile(mavenProject); if (!bundleFile.exists()) { for (DownloadListener listener : listeners) { try { listener.failure(bundleFile, "Could not get bundle file for " + bsn + ":" + version); } catch (Throwable t) { logger.logError("Download listener error", t); } } return null; } for (DownloadListener listener : listeners) { try { listener.success(bundleFile); } catch (Throwable t) { logger.logError("Download listener error", t); } } return bundleFile; }
Source:
<code>public static Function<Resource, Double> toDoubleResourceValue() { return new Function<Resource, Double>() { @Override <START> public Double apply(@Nullable Resource resource) { <END> return resourceValueDouble(Optional.fromNullable(resource)).or(0.0); } }; }</code><technical_language>Please mark resource parameter final</technical_language>

Target:
public static Function<Resource, Double> toDoubleResourceValue() { return ToDoubleResourceValue.INSTANCE; }
Source:
<code>private Mono<PagedResponse<DataPointAnomaly>> listAnomaliesForDetectionConfigSinglePageAsync( String detectionConfigurationId, OffsetDateTime startTime, OffsetDateTime endTime, ListAnomaliesDetectedOptions options, Context context) { Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required."); Objects.requireNonNull(startTime, "'startTime' is required."); Objects.requireNonNull(endTime, "'endTime' is required."); DetectionAnomalyResultQuery query = new DetectionAnomalyResultQuery() .setStartTime(startTime) .setEndTime(endTime); <START> if (options.getFilter() != null) { <END> DetectionAnomalyFilterCondition innerFilter = AnomalyTransforms.toInnerFilter(options.getFilter(), logger); if (innerFilter != null) { query.setFilter(innerFilter); } } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, METRICS_ADVISOR_TRACING_NAMESPACE_VALUE); return service.getAnomaliesByAnomalyDetectionConfigurationSinglePageAsync( UUID.fromString(detectionConfigurationId), query, options.getSkip(), options.getTop(), withTracing) .doOnRequest(ignoredValue -> logger.info("Listing anomalies detected")) .doOnSuccess(response -> logger.info("Listed anomalies {}", response)) .doOnError(error -> logger.warning("Failed to list the anomalies detected", error)) .map(response -> AnomalyTransforms.fromInnerPagedResponse(response)); }</code><technical_language>check for option is null invoking getFilter</technical_language>

Target:
private Mono<PagedResponse<DataPointAnomaly>> listAnomaliesForDetectionConfigSinglePageAsync( String detectionConfigurationId, OffsetDateTime startTime, OffsetDateTime endTime, ListAnomaliesDetectedOptions options, Context context) { Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required."); Objects.requireNonNull(startTime, "'startTime' is required."); Objects.requireNonNull(endTime, "'endTime' is required."); DetectionAnomalyResultQuery query = new DetectionAnomalyResultQuery() .setStartTime(startTime) .setEndTime(endTime); if (options == null) { options = new ListAnomaliesDetectedOptions(); } if (options.getFilter() != null) { DetectionAnomalyFilterCondition innerFilter = AnomalyTransforms.toInnerFilter(options.getFilter(), logger); if (innerFilter != null) { query.setFilter(innerFilter); } } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, METRICS_ADVISOR_TRACING_NAMESPACE_VALUE); return service.getAnomaliesByAnomalyDetectionConfigurationSinglePageAsync( UUID.fromString(detectionConfigurationId), query, options.getSkip(), options.getTop(), withTracing) .doOnRequest(ignoredValue -> logger.info("Listing anomalies detected")) .doOnSuccess(response -> logger.info("Listed anomalies {}", response)) .doOnError(error -> logger.warning("Failed to list the anomalies detected", error)) .map(response -> AnomalyTransforms.fromInnerPagedResponse(response)); }
Source:
<code>public ImmutableIgniteableData copy() { <START> return new ImmutableSpongeIgniteableData(this.fireTicks, this.fireDelay); <END> }</code><technical_language>return this. need more copies</technical_language>

Target:
public ImmutableIgniteableData copy() { return this; }
Source:
<code>public static TableSchema projectSchema(TableSchema tableSchema, int[][] projectedFields) { checkArgument(containsPhysicalColumnsOnly(tableSchema), "Projection is only supported for physical columns."); TableSchema.Builder schemaBuilder = TableSchema.builder(); List<TableColumn> tableColumns = tableSchema.getTableColumns(); Map<String, String> nameDomain = new HashMap<>(); String exceptionTemplate = "Get name conflicts for origin fields %s and %s with new name `%s`. " + "When pushing projection into scan, we will concatenate top level names with delimiter '_'. " + "Please rename the origin field names when creating table."; String originFullyQualifiedName; String newName; for (int[] fieldPath : projectedFields) { if (fieldPath.length == 1) { TableColumn column = tableColumns.get(fieldPath[0]); newName = column.getName(); originFullyQualifiedName = String.format("`%s`", column.getName()); if (nameDomain.containsKey(column.getName())) { <START> throw new TableException( <END> String.format(exceptionTemplate, nameDomain.get(newName), originFullyQualifiedName, newName)); } schemaBuilder.field(newName, column.getType()); nameDomain.put(newName, originFullyQualifiedName); } else { TableColumn column = tableColumns.get(fieldPath[0]); DataType dataType = column.getType(); StringBuilder nameBuilder = new StringBuilder(column.getName()); StringBuilder originQualifiedNameBuilder = new StringBuilder("`" + column.getName() + "`"); for (int i = 1; i < fieldPath.length; i++) { RowType rowType = (RowType) dataType.getLogicalType(); nameBuilder.append('_').append(rowType.getFieldNames().get(fieldPath[i])); originQualifiedNameBuilder.append(".`") .append(rowType.getFieldNames().get(fieldPath[i])) .append("`"); dataType = dataType.getChildren().get(fieldPath[i]); } originFullyQualifiedName = originQualifiedNameBuilder.toString(); newName = nameBuilder.toString(); if (nameDomain.containsKey(newName)) { throw new TableException( String.format(exceptionTemplate, originFullyQualifiedName, nameDomain.get(newName), newName)); } schemaBuilder.field(newName, dataType); nameDomain.put(newName, originFullyQualifiedName); } } return schemaBuilder.build(); }</code><technical_language>resolve conflicts adding postfix</technical_language>

Target:
public static TableSchema projectSchema(TableSchema tableSchema, int[][] projectedFields) { checkArgument(containsPhysicalColumnsOnly(tableSchema), "Projection is only supported for physical columns."); TableSchema.Builder builder = TableSchema.builder(); FieldsDataType fields = (FieldsDataType) DataTypeUtils.projectRow(tableSchema.toRowDataType(), projectedFields); RowType topFields = (RowType) fields.getLogicalType(); for (int i = 0; i < topFields.getFieldCount(); i++) { builder.field(topFields.getFieldNames().get(i), fields.getChildren().get(i)); } return builder.build(); }
Source:
<code>public void vuapResolvedStateIsNotMute(Page page, String slot, String videoIframeSelector) { <START> AdsBaseObject ads = new AdsBaseObject(driver, page.getUrl() + "&" + TURN_ON_RESOLVED_STATE); <END> final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); scrollToSlot(slot, ads); vuap.replay(); vuap.mute(); VuapAssertions.verifyVideoUnmuteAndMute(vuap); }</code><technical_language>& here? (not ?)</technical_language>

Target:
public void vuapResolvedStateIsNotMute(Page page, String slot, String videoIframeSelector) { AdsBaseObject ads = new AdsBaseObject(driver, this.urlBuilder.getUrlForPage(page, TURN_ON_RESOLVED_STATE)); final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); scrollToSlot(slot, ads); vuap.replay(); vuap.mute(); VuapAssertions.verifyVideoUnmuteAndMute(vuap); }
Source:
<code><START> public void testGetters() { <END> org.apache.bookkeeper.client.api.LedgerMetadata metadata = new LedgerMetadata( 3, 2, 1, DigestType.CRC32, passwd, Collections.emptyMap(), false); assertEquals(3, metadata.getEnsembleSize()); assertEquals(2, metadata.getWriteQuorumSize()); assertEquals(1, metadata.getAckQuorumSize()); assertEquals(org.apache.bookkeeper.client.api.DigestType.CRC32, metadata.getDigestType()); assertEquals(Collections.emptyMap(), metadata.getCustomMetadata()); assertEquals(-1L, metadata.getCtime()); assertEquals(-1L, metadata.getLastEntryId()); assertEquals(0, metadata.getLength()); assertFalse(metadata.isSealed()); assertTrue(metadata.getAllEnsembles().isEmpty()); try { metadata.getEnsembleAt(99L); fail("Should fail to retrieve ensemble if ensembles is empty"); } catch (NoSuchElementException e) { } }</code><technical_language>tests (BookKeeperBuildersTest) in I a cast LedgerHandle access LedgerMetadata, good update</technical_language>

Target:
public void testGetters() { org.apache.bookkeeper.client.api.LedgerMetadata metadata = new LedgerMetadata( 3, 2, 1, DigestType.CRC32, passwd, Collections.emptyMap(), false); assertEquals(3, metadata.getEnsembleSize()); assertEquals(2, metadata.getWriteQuorumSize()); assertEquals(1, metadata.getAckQuorumSize()); assertEquals(org.apache.bookkeeper.client.api.DigestType.CRC32, metadata.getDigestType()); assertEquals(Collections.emptyMap(), metadata.getCustomMetadata()); assertEquals(-1L, metadata.getCtime()); assertEquals(-1L, metadata.getLastEntryId()); assertEquals(0, metadata.getLength()); assertFalse(metadata.isClosed()); assertTrue(metadata.getAllEnsembles().isEmpty()); try { metadata.getEnsembleAt(99L); fail("Should fail to retrieve ensemble if ensembles is empty"); } catch (NoSuchElementException e) { } }
Source:
<code>private static void printCustomerDetails(List<CustomerDto> allCustomers) { <START> allCustomers.forEach(customer -> System.out.println(customer.getFirstName())); <END> }</code><technical_language>System.println, instead add a logger in other examples</technical_language>

Target:
private static void printCustomerDetails(List<CustomerDto> allCustomers) { allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName())); }
Source:
<code>public boolean deleteDomain(DomainVO domain, Boolean cleanup) { GlobalLock lock = getGlobalLock("AccountCleanup"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return false; } if (!lock.lock(30)) { s_logger.debug("Couldn't lock the db"); return false; } try { s_logger.debug("Marking domain id=" + domain.getId() + " as " + Domain.State.Inactive + " before actually deleting it"); domain.setState(Domain.State.Inactive); _domainDao.update(domain.getId(), domain); try { long ownerId = domain.getAccountId(); if (BooleanUtils.toBoolean(cleanup)) { <START> if (!cleanupDomain(domain.getId(), ownerId)) { <END> rollBackState = true; CloudRuntimeException e = new CloudRuntimeException("Failed to clean up domain resources and sub domains, delete failed on domain " + domain.getName() + " (id: " + domain.getId() + ")."); e.addProxyObject(domain.getUuid(), "domainId"); throw e; } } else { checkDomainAccountsNetworksAndResourcesBeforeRemoving(domain); } cleanupDomainOfferings(domain.getId()); CallContext.current().putContextParameter(Domain.class, domain.getUuid()); return true; } catch (Exception ex) { s_logger.error("Exception deleting domain with id " + domain.getId(), ex); if (ex instanceof CloudRuntimeException) throw (CloudRuntimeException)ex; else return false; } finally { if (rollBackState) { s_logger.debug("Changing domain id=" + domain.getId() + " state back to " + Domain.State.Active + " because it can't be removed due to resources referencing to it"); domain.setState(Domain.State.Active); _domainDao.update(domain.getId(), domain); } } } finally { lock.unlock(); rollBackState = false; } }</code><technical_language>@nvazquez improve greatly this method. do feel another code extraction? lines 312-319 easily extracted a method, enabling reduction of lines in try/try/finally/finally blocks</technical_language>

Target:
public boolean deleteDomain(DomainVO domain, Boolean cleanup) { GlobalLock lock = getGlobalLock("AccountCleanup"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return false; } if (!lock.lock(30)) { s_logger.debug("Couldn't lock the db"); return false; } try { s_logger.debug("Marking domain id=" + domain.getId() + " as " + Domain.State.Inactive + " before actually deleting it"); domain.setState(Domain.State.Inactive); _domainDao.update(domain.getId(), domain); try { long ownerId = domain.getAccountId(); if (BooleanUtils.toBoolean(cleanup)) { tryCleanupDomain(domain, ownerId); } else { removeDomainWithNoAccountsForCleanupNetworksOrDedicatedResources(domain); } cleanupDomainOfferings(domain.getId()); CallContext.current().putContextParameter(Domain.class, domain.getUuid()); return true; } catch (Exception ex) { s_logger.error("Exception deleting domain with id " + domain.getId(), ex); if (ex instanceof CloudRuntimeException) { rollbackDomainState(domain); throw (CloudRuntimeException)ex; } else return false; } } finally { lock.unlock(); } }
Source:
<code>public static ScalarFunction getRoundExpression(List<Expression> children) throws SQLException { final Expression firstChild = children.get(0); final PDataType firstChildDataType = firstChild.getDataType(); final Object obj = children.get(1); TimeUnit tu = null; if(obj instanceof LiteralExpression) { <START> tu = TimeUnit.getTimeUnitIfValid((LiteralExpression)obj); <END> } if(firstChildDataType.isCoercibleTo(PDataType.DATE)) { return new RoundDateExpression(children); } else if(firstChildDataType == PDataType.TIMESTAMP) { if(tu == TimeUnit.MILLISECOND) { return new RoundTimestampExpression(children); } return new RoundDateExpression(children); } else if(firstChildDataType.isCoercibleTo(PDataType.DECIMAL)) { return new RoundDecimalExpression(children); } else { throw new TypeMismatchException(firstChildDataType, "1"); } }</code><technical_language>Move this TIMESTAMP if statement below. need TimeUnit.getTimeUnit call, fine throw if invalid below</technical_language>

Target:
public static ScalarFunction getRoundExpression(List<Expression> children) throws SQLException { final Expression firstChild = children.get(0); final PDataType firstChildDataType = firstChild.getDataType(); if(firstChildDataType.isCoercibleTo(PDataType.DATE)) { return new RoundDateExpression(children); } else if (firstChildDataType == PDataType.TIMESTAMP || firstChildDataType == PDataType.UNSIGNED_TIMESTAMP) { Object secondChild = ((LiteralExpression)children.get(1)).getValue(); String timeUnit = secondChild == null ? null : secondChild.toString(); TimeUnit tu = TimeUnit.getTimeUnit(timeUnit); LiteralExpression multiplierExpr = (LiteralExpression)children.get(2); if(tu == TimeUnit.MILLISECOND && ((Number)multiplierExpr.getValue()).intValue() == 1) { return RoundTimestampExpression.create(firstChild, multiplierExpr); } return new RoundDateExpression(children); } else if(firstChildDataType.isCoercibleTo(PDataType.DECIMAL)) { return new RoundDecimalExpression(children); } else { throw new TypeMismatchException(firstChildDataType, "1"); } }
Source:
<code>private void processInstrumented(VCastDataStore dataStore, VCastInstrumentedFile instrumentedFile) throws Exception { VCastSourceFileJoin sourceFile = null; try { sourceFile = dataStore.getSourceFileJoin(instrumentedFile); } catch (OseeCoreException ex) { throw new OseeCoreException(ex, "SQL error while reading source_files for instrumented_file id:%s", instrumentedFile.getId()); } if (sourceFile != null) { int fileNum = sourceFile.getUnitIndex(); String lisFileName_badPath = instrumentedFile.getLISFile(); if (!Strings.isValid(lisFileName_badPath)) { } String normalizedPath = lisFileName_badPath.replaceAll("\\\\", "/"); File f = new File(normalizedPath); String lisFileName = f.getName(); VCastLisFileParser lisFileParser = new VCastLisFileParser(lisFileName, vCastDir); Collection<VCastFunction> functions = Collections.emptyList(); try { functions = dataStore.getFunctions(instrumentedFile); } catch (OseeCoreException ex) { <START> throw new OseeCoreException(ex, "SQL error while reading functions for instrumented_file id:", <END> instrumentedFile.getId()); } for (VCastFunction function : functions) { processFunction(lisFileName, lisFileParser, fileNum, dataStore, instrumentedFile, function); } } }</code><technical_language>getId call wont get put exception dont a formatter character in there... add a %d %s depending getId returns</technical_language>

Target:
private void processInstrumented(VCastDataStore dataStore, VCastInstrumentedFile instrumentedFile) throws Exception { VCastSourceFileJoin sourceFile = null; try { sourceFile = dataStore.getSourceFileJoin(instrumentedFile); } catch (OseeCoreException ex) { throw new OseeCoreException(ex, "SQL error while reading source_files for instrumented_file id:%s", instrumentedFile.getId()); } if (sourceFile != null) { int fileNum = sourceFile.getUnitIndex(); String lisFileName_badPath = instrumentedFile.getLISFile(); if (!Strings.isValid(lisFileName_badPath)) { } String normalizedPath = lisFileName_badPath.replaceAll("\\\\", "/"); File f = new File(normalizedPath); String lisFileName = f.getName(); VCastLisFileParser lisFileParser = new VCastLisFileParser(lisFileName, vCastDir); Collection<VCastFunction> functions = Collections.emptyList(); try { functions = dataStore.getFunctions(instrumentedFile); } catch (OseeCoreException ex) { throw new OseeCoreException(ex, "SQL error while reading functions for instrumented_file id: %d", instrumentedFile.getId()); } for (VCastFunction function : functions) { processFunction(lisFileName, lisFileParser, fileNum, dataStore, instrumentedFile, function); } } }
Source:
<code>public void clearStatistics(Collection<String> cacheNames) throws IgniteCheckedException { Collection<IgniteInternalCache> caches = manageStatisticsCaches(cacheNames); Collection<String> globalCaches = new HashSet<>(caches.size()); for (IgniteInternalCache cache : caches) { <START> if(!cache.context().isLocal() && cache.clusterMxBean().isStatisticsEnabled()) <END> globalCaches.add(cache.name()); } if (globalCaches.isEmpty()) return; CacheStatisticsClearMessage msg = new CacheStatisticsClearMessage(UUID.randomUUID(), globalCaches); EnableStatisticsFuture fut = new EnableStatisticsFuture(msg.requestId()); manageStatisticsFuts.put(msg.requestId(), fut); ctx.grid().context().discovery().sendCustomEvent(msg); fut.get(); }</code><technical_language>Need space brace</technical_language>

Target:
public void clearStatistics(Collection<String> cacheNames) throws IgniteCheckedException { Collection<IgniteInternalCache> caches = manageStatisticsCaches(cacheNames); Collection<String> globalCaches = new HashSet<>(U.capacity(caches.size())); for (IgniteInternalCache cache : caches) { if (!cache.context().isLocal()) globalCaches.add(cache.name()); } if (globalCaches.isEmpty()) return; CacheStatisticsClearMessage msg = new CacheStatisticsClearMessage(UUID.randomUUID(), globalCaches); EnableStatisticsFuture fut = new EnableStatisticsFuture(msg.requestId()); manageStatisticsFuts.put(msg.requestId(), fut); ctx.grid().context().discovery().sendCustomEvent(msg); fut.get(); }
Source:
<code>synchronized void start(Context context, long googleApiConnectTimeout, boolean force) { if (isStarted && !force) { return; } isStarted = true; if (PlayServicesHelpers.isAvailable(context)) { Log.d(TAG, "Configuring location provider for Google Play Services"); stopLocationUpdatesWithPlayServices(); mGoogleApiClient = new GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); googleApiStartupLatch = new CountDownLatch(1); mGoogleApiClient.connect(); if (googleApiConnectTimeout > 0) { try { googleApiStartupLatch.await(googleApiConnectTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } } else { Log.d(TAG, "Configuring the default Android location provider"); stopLocationUpdatesWithoutPlayServices(); mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); if (mLocationManager == null) { Log.e(TAG, "Cannot retrieve the location manager"); return; } startLocationUpdatesWithoutPlayServices(); } }</code><technical_language>Is Log.e better</technical_language>

Target:
synchronized void start(Context context, long googleApiConnectTimeout, boolean force) { if (isStarted && !force) { return; } isStarted = true; boolean isPlayServicesAvailable = PlayServicesHelpers.isAvailable(context); if (isPlayServicesAvailable) { Log.d(TAG, "Configuring location provider for Google Play Services"); stopLocationUpdatesWithPlayServices(); mGoogleApiClient = new GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); googleApiStartupLatch = new CountDownLatch(1); mGoogleApiClient.connect(); if (googleApiConnectTimeout > 0) { try { googleApiStartupLatch.await(googleApiConnectTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Log.w(TAG, e); } } } if (!isPlayServicesAvailable || mGoogleApiClient == null) { Log.d(TAG, "Configuring the default Android location provider"); stopLocationUpdatesWithoutPlayServices(); mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); if (mLocationManager == null) { Log.e(TAG, "Cannot retrieve the location manager"); return; } startLocationUpdatesWithoutPlayServices(); } }