auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized Connection getDatabaseConnection(boolean needWritable) throws SQLException { if (activeConnection != null && !activeConnection.isValid(5)) { reset(); activeConnection = null; connectedEndpoint = null; } if (activeConnection != null && !isBetterEndpoint(sortedDbEndpoints.get(0), connectedEndpoint)) { return activeConnection; } Pair<DbEndpoint, Connection> endpointConnectionPair = connectToBestAvailableEndpoint(needWritable); if (connectedEndpoint == endpointConnectionPair.getFirst()) { logger.debug("Still connected to {}", connectedEndpoint.getUrl()); } else { connectedEndpoint = endpointConnectionPair.getFirst(); String qualifier = connectedEndpoint.isWriteable() ? "writable" : "read-only"; logger.info("Connected to enpoint: {}", qualifier, connectedEndpoint.getUrl()); closeQuietly(activeConnection); activeConnection = endpointConnectionPair.getSecond(); } return activeConnection; }

Target:
public synchronized Connection getDatabaseConnection(boolean needWritable) throws SQLException { if (activeConnection != null && !activeConnection.isValid(5)) { closeActiveConnection(); activeConnection = null; connectedEndpoint = null; } if (activeConnection != null && !isBetterEndpoint(sortedDbEndpoints.get(0), connectedEndpoint)) { return activeConnection; } Pair<DbEndpoint, Connection> endpointConnectionPair = connectToBestAvailableEndpoint(needWritable); if (connectedEndpoint == endpointConnectionPair.getFirst()) { logger.debug("Still connected to {}", connectedEndpoint.getUrl()); } else { connectedEndpoint = endpointConnectionPair.getFirst(); String qualifier = connectedEndpoint.isWriteable() ? "writable" : "read-only"; logger.info("Connected to enpoint: {}", qualifier, connectedEndpoint.getUrl()); closeActiveConnection(); activeConnection = endpointConnectionPair.getSecond(); } return activeConnection; }
Source:
private Consumer<OcflObjectUpdater> constructCommitUpdater(final boolean updatingObject) { final DIGEST_ALGORITHM fcrepoDigestAlg = getObjectDigestAlgorithm(); final DigestAlgorithm ocflDigestAlg = translateFedoraDigestToOcfl(fcrepoDigestAlg); final OcflOption[] ocflOptions; if (updatingObject) { ocflOptions = new OcflOption[] { MOVE_SOURCE, OVERWRITE }; } else { ocflOptions = new OcflOption[] { MOVE_SOURCE }; } return updater -> { if (updatingObject) { deletePaths.forEach(updater::removeFile); } if (isStagingEmpty()) { return; } try { Files.walk(stagingPath) .filter(Files::isRegularFile) .forEach(filePath -> { final var relativePath = stagingPath.relativize(filePath); final var subpath = FileUtil.pathToStringStandardSeparator(relativePath); updater.addPath(filePath, subpath, ocflOptions); final var digest = subpathToDigest.get(subpath); if (digest != null) { try { updater.addFileFixity(subpath, ocflDigestAlg, digest); } catch (final FixityCheckException e) { throw new PersistentStorageRuntimeException("Transmission of file " + filePath + " failed due to fixity check failure: " + e.getMessage()); } } }); } catch (final IOException e) { log.error("Failed to read staging path {}", stagingPath, e); } }; }

Target:
private Consumer<OcflObjectUpdater> constructCommitUpdater(final boolean updatingObject) { final DIGEST_ALGORITHM fcrepoDigestAlg = getObjectDigestAlgorithm(); final DigestAlgorithm ocflDigestAlg = translateFedoraDigestToOcfl(fcrepoDigestAlg); final OcflOption[] ocflOptions; if (updatingObject) { ocflOptions = new OcflOption[] { MOVE_SOURCE, OVERWRITE }; } else { ocflOptions = new OcflOption[] { MOVE_SOURCE }; } return updater -> { if (updatingObject) { deletePaths.forEach(updater::removeFile); } if (isStagingEmpty()) { return; } updater.addPath(stagingPath, ocflOptions); subpathToDigest.forEach((subpath, digest) -> { final String normalizedPath = FileUtil.pathToStringStandardSeparator(Paths.get(subpath)); try { updater.addFileFixity(normalizedPath, ocflDigestAlg, digest); } catch (final FixityCheckException e) { throw new PersistentStorageRuntimeException("Transmission of file " + subpath + " failed due to fixity check failure: " + e.getMessage()); } }); }; }
Source:
public boolean updateParams(HashMap<String, Object> params) { if (this.parameters == null){ this.parameters = new HashMap<String, Object>(); } this.parameters = JainSipConfiguration.mergeParameters(this.parameters, params); if (storageManagerPreferences == null){ storageManagerPreferences = new StorageManagerPreferences(this); } saveParams(storageManagerPreferences, parameters); if (signalingClient != null) { signalingClient.reconfigure(params); registerForPush(true); } else { this.clearPushData = true; connectSignaling(parameters); / / } return true; }

Target:
public boolean updateParams(HashMap<String, Object> params) { this.parameters = JainSipConfiguration.mergeParameters(this.parameters, params); if (storageManagerPreferences == null){ storageManagerPreferences = new StorageManagerPreferences(this); } saveParams(storageManagerPreferences, parameters); signalingClient.reconfigure(params); registerForPush(true); return true; }
Source:
public TestClass(Class<?> klass) { fClass = klass; if (klass != null && klass.getConstructors().length > 1) { throw new IllegalArgumentException( "Test class can only have one constructor"); } Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkMethod>>(); Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkField>>(); for (Class<?> eachClass : getSuperClasses(fClass)) { for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) { addToAnnotationLists(new FrameworkMethod(eachMethod), methodsForAnnotations); } for (Field eachField : getSortedDeclaredFields(eachClass)) { addToAnnotationLists(new FrameworkField(eachField), fieldsForAnnotations); } } Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotationsWithUnmodifiableLists = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkMethod>>(); convertListValuesToBeUnmodifiable(methodsForAnnotations, methodsForAnnotationsWithUnmodifiableLists); Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotationsWithUnmodifiableLists = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkField>>(); convertListValuesToBeUnmodifiable(fieldsForAnnotations, fieldsForAnnotationsWithUnmodifiableLists); fMethodsForAnnotations = Collections.unmodifiableMap(methodsForAnnotationsWithUnmodifiableLists); fFieldsForAnnotations = Collections.unmodifiableMap(fieldsForAnnotationsWithUnmodifiableLists); }

Target:
public TestClass(Class<?> klass) { fClass = klass; if (klass != null && klass.getConstructors().length > 1) { throw new IllegalArgumentException( "Test class can only have one constructor"); } Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkMethod>>(); Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations = new LinkedHashMap<Class<? extends Annotation>, List<FrameworkField>>(); for (Class<?> eachClass : getSuperClasses(fClass)) { for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) { addToAnnotationLists(new FrameworkMethod(eachMethod), methodsForAnnotations); } for (Field eachField : getSortedDeclaredFields(eachClass)) { addToAnnotationLists(new FrameworkField(eachField), fieldsForAnnotations); } } fMethodsForAnnotations = makeDeeplyUnmodifiable(methodsForAnnotations); fFieldsForAnnotations = makeDeeplyUnmodifiable(fieldsForAnnotations); }
Source:
private void validateSchemaOrSurveyExists(SharedModuleMetadata metadata) { SharedModuleType type = metadata.getModuleType(); if (type == SharedModuleType.SCHEMA) { String schemaId = metadata.getSchemaId(); int schemaRevision = metadata.getSchemaRevision(); try { uploadSchemaService.getUploadSchemaByIdAndRev(SHARED_STUDY_ID, schemaId, schemaRevision); } catch (EntityNotFoundException e) { throw new BadRequestException("Upload schema " + schemaId + " referred does not exist: " + e); } } else if (type == SharedModuleType.SURVEY) { String surveyGuid = metadata.getSurveyGuid(); long createdOn = metadata.getSurveyCreatedOn(); Survey survey = surveyService.getSurvey(null, new GuidCreatedOnVersionHolderImpl(surveyGuid, createdOn), false, false); if (survey == null) { throw new BadRequestException("Survey " + surveyGuid + " referred does not exist."); } } }

Target:
private void validateSchemaOrSurveyExists(SharedModuleMetadata metadata) { SharedModuleType type = metadata.getModuleType(); if (type == SharedModuleType.SCHEMA) { String schemaId = metadata.getSchemaId(); int schemaRevision = metadata.getSchemaRevision(); try { uploadSchemaService.getUploadSchemaByIdAndRev(SHARED_STUDY_ID, schemaId, schemaRevision); } catch (EntityNotFoundException e) { throw new BadRequestException("Upload schema " + schemaId + " referred does not exist: " + e); } } else if (type == SharedModuleType.SURVEY) { String surveyGuid = metadata.getSurveyGuid(); long createdOn = metadata.getSurveyCreatedOn(); Survey survey = surveyService.getSurvey(SHARED_STUDY_ID, new GuidCreatedOnVersionHolderImpl(surveyGuid, createdOn), false, false); if (survey == null) { throw new BadRequestException("Survey " + surveyGuid + " referred does not exist."); } } }
Source:
public void onHeaderCheck(final ApiResult result, final URL apiURL) { if (!WIKIPEDIA_ZERO_DEV_MODE_ON || acquiringCarrierMessage) { return; } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { boolean responseZeroState = result.getHeaders().containsKey("X-CS"); if (responseZeroState) { String xcs = result.getHeaders().get("X-CS").get(0); if (!xcs.equals(carrierString)) { identifyZeroCarrier(xcs); } } else if (zeroEnabled && supportsZeroHeaders(apiURL.getHost())) { carrierString = ""; carrierMessage = null; zeroEnabled = false; app.getBus().post(new WikipediaZeroStateChangeEvent()); } } }); }

Target:
public void onHeaderCheck(final ApiResult result, final URL apiURL) { if (!WIKIPEDIA_ZERO_DEV_MODE_ON || acquiringCarrierMessage) { return; } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (hostSupportsZeroHeaders(apiURL.getHost())) { boolean responseZeroState = result.getHeaders().containsKey("X-CS"); if (responseZeroState) { String xcs = result.getHeaders().get("X-CS").get(0); if (!xcs.equals(carrierString)) { identifyZeroCarrier(xcs); } } else if (zeroEnabled) { carrierString = ""; carrierMessage = null; zeroEnabled = false; app.getBus().post(new WikipediaZeroStateChangeEvent()); } } } }); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JsonArrayEntry other = (JsonArrayEntry) obj; if (booleanValue == null) { if (other.booleanValue != null) return false; } else if (!booleanValue.equals(other.booleanValue)) return false; if (floatValue == null) { if (other.floatValue != null) return false; } else if (!floatValue.equals(other.floatValue)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (objectLinkValue == null) { if (other.objectLinkValue != null) return false; } else if (!objectLinkValue.equals(other.objectLinkValue)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; if (!Objects.equals(time, other.time)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JsonArrayEntry other = (JsonArrayEntry) obj; if (booleanValue == null) { if (other.booleanValue != null) return false; } else if (!booleanValue.equals(other.booleanValue)) return false; if (floatValue == null) { if (other.floatValue != null) return false; } else if (!floatValue.equals(other.floatValue)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (objectLinkValue == null) { if (other.objectLinkValue != null) return false; } else if (!objectLinkValue.equals(other.objectLinkValue)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; if (time == null) { if (other.time != null) return false; } else if (!time.equals(other.time)) return false; return true; }
Source:
public void start() throws IOException { server = new MockWebServer(); server.play(); ApiContext<ProfitBricksApi> ctx = ContextBuilder.newBuilder("profitbricks-rest") .credentials("", MOCK_BEARER_TOKEN) .endpoint(url("")) .modules(modules) .overrides(overrides()) .build(); json = ctx.utils().injector().getInstance(Json.class); api = ctx.getApi(); }

Target:
public void start() throws IOException { server = new MockWebServer(); server.play(); ApiContext<ProfitBricksApi> ctx = ContextBuilder.newBuilder("profitbricks-rest") .credentials("username", "password") .endpoint(url("")) .modules(modules) .overrides(overrides()) .build(); json = ctx.utils().injector().getInstance(Json.class); api = ctx.getApi(); }
Source:
public void whenUnableToAcquireShardOnLastTaskRescheduleAfterMaxPause() throws Exception { ScalingSweepTaskScheduler schedulerWithRealDelay = createScheduler(new SweepDelay(1L), Duration.ZERO); when(sweepIteration.call()).thenReturn(SweepIterationResults.unableToAcquireShard(), SUCCESS_MEDIUM); schedulerWithRealDelay.start(1); deterministicScheduler.tick(INITIAL_DELAY + SweepDelay.DEFAULT_MAX_PAUSE_MILLIS + 2, TimeUnit.MILLISECONDS); verify(sweepIteration, times(1 + 3)).call(); }

Target:
public void whenUnableToAcquireShardOnLastTaskRescheduleAfterMaxPause() throws Exception { when(sweepIteration.call()).thenReturn(SweepIterationResults.unableToAcquireShard()); schedulerWithDelay.start(10); runSweepIterations(1 + 9, SweepDelay.DEFAULT_MAX_PAUSE_MILLIS); verify(sweepIteration, times(10 + 9 * 1)).call(); }
Source:
private boolean close(final long timeoutMs) { if (!setState(State.PENDING_SHUTDOWN)) { ENDING_SHUTDOWN log.info("Already in the pending shutdown state, wait to complete shutdown"); } else { stateDirCleaner.shutdownNow(); final Thread shutdownThread = new Thread(() -> { for (final StreamThread thread : threads) { thread.shutdown(); } for (final StreamThread thread : threads) { try { if (!thread.isRunning()) { thread.join(); } } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } if (globalStreamThread != null) { globalStreamThread.shutdown(); } if (globalStreamThread != null && !globalStreamThread.stillRunning()) { try { globalStreamThread.join(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } globalStreamThread = null; } adminClient.close(); metrics.close(); setState(State.NOT_RUNNING); }, "kafka-streams-close-thread"); if (RecordingLevel.forName(config.getString(METRICS_RECORDING_LEVEL_CONFIG)) == RecordingLevel.DEBUG) { rocksDBMetricsRecordingTriggerThread.shutdownNow(); } shutdownThread.setDaemon(true); shutdownThread.start(); } if (waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped completely"); return true; } else { log.info("Streams client cannot stop completely within the timeout"); return false; } }

Target:
private boolean close(final long timeoutMs) { if (!setState(State.PENDING_SHUTDOWN)) { ENDING_SHUTDOWN log.info("Already in the pending shutdown state, wait to complete shutdown"); } else { stateDirCleaner.shutdownNow(); if (rocksDBMetricsRecordingService != null) { rocksDBMetricsRecordingService.shutdownNow(); } final Thread shutdownThread = new Thread(() -> { for (final StreamThread thread : threads) { thread.shutdown(); } for (final StreamThread thread : threads) { try { if (!thread.isRunning()) { thread.join(); } } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } if (globalStreamThread != null) { globalStreamThread.shutdown(); } if (globalStreamThread != null && !globalStreamThread.stillRunning()) { try { globalStreamThread.join(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } globalStreamThread = null; } adminClient.close(); metrics.close(); setState(State.NOT_RUNNING); }, "kafka-streams-close-thread"); shutdownThread.setDaemon(true); shutdownThread.start(); } if (waitOnState(State.NOT_RUNNING, timeoutMs)) { log.info("Streams client stopped completely"); return true; } else { log.info("Streams client cannot stop completely within the timeout"); return false; } }
Source:
public static Slice stMultiPoint(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { MultiPoint multipoint = new MultiPoint(); for (int i = 0; i < input.getPositionCount(); i++) { Slice slice = GEOMETRY.getSlice(input, i); if (slice.getInput().available() == 0) { continue; } OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("ST_MultiPoint takes only an array of valid points, %s was passed", geometry.geometryType())); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { continue; } multipoint.add(point.X(), point.Y()); } if (multipoint.getPointCount() < 1) { return null; } OGCGeometry geometry = createFromEsriGeometry(multipoint, null); return serialize(geometry); }

Target:
public static Slice stMultiPoint(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { MultiPoint multipoint = new MultiPoint(); for (int i = 0; i < input.getPositionCount(); i++) { if (input.isNull(i)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "ST_MultiPoint takes only an array of valid points, NULL point was passed"); } Slice slice = GEOMETRY.getSlice(input, i); OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("ST_MultiPoint takes only an array of valid points, %s was passed", geometry.geometryType())); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { continue; } multipoint.add(point.X(), point.Y()); } if (multipoint.getPointCount() < 1) { return null; } return serialize(createFromEsriGeometry(multipoint, null, true)); }
Source:
public ObisCodeValues convertFrom(com.alliander.osgp.domain.core.valueobjects.smartmetering.ObisCodeValues source, Type<ObisCodeValues> destinationType) { final ObisCodeValues result = new ObisCodeValues(); result.setA(source.getA()); result.setB(source.getB()); result.setC(source.getC()); result.setD(source.getD()); result.setE(source.getE()); result.setF(source.getF()); return result; }

Target:
public ObisCodeValues convertFrom(com.alliander.osgp.domain.core.valueobjects.smartmetering.ObisCodeValues source, Type<ObisCodeValues> destinationType) { final ObisCodeValues result = new ObisCodeValues(); result.setA((short)(source.getA() & 0xFF)); result.setB((short)(source.getB() & 0xFF)); result.setC((short)(source.getC() & 0xFF)); result.setD((short)(source.getD() & 0xFF)); result.setE((short)(source.getE() & 0xFF)); result.setF((short)(source.getF() & 0xFF)); return result; }
Source:
public String getMessage(Bundle bundle, String value) { String result = value; if (bundle != null && result != null && result.startsWith(PERCENT)) { if (bundle != null && result != null && result.startsWith(PERCENT + PERCENT)) { return result.replaceFirst(PERCENT, EMPTY); } try { result = Platform.getResourceBundle(bundle).getString(result.replaceFirst(PERCENT, EMPTY)); } catch (MissingResourceException mre) { DslCommonPlugin.INSTANCE.log(mre); } } return result; }

Target:
public String getMessage(Bundle bundle, String value) { String result = value; if (bundle != null && result != null && result.startsWith(PERCENT)) { if (bundle != null && result != null && result.startsWith(PERCENT + PERCENT)) { return result.replaceFirst(PERCENT, EMPTY); } try { result = Platform.getResourceBundle(bundle).getString(result.substring(PERCENT.length())); } catch (MissingResourceException mre) { DslCommonPlugin.INSTANCE.log(new Status(IStatus.WARNING, bundle.getSymbolicName(), 0, "The key " + value + "has not been found in the properties file for label localization", mre)); } } return result; }
Source:
public void testProteinSubstitutionScoresModel() { String testVariantId = "rs370478"; String url = "/v1/variants/" + testVariantId + "/info?species=mmusculus_grcm38"; List<VariantWithSamplesAndAnnotation> variants = WSTestHelpers.testRestTemplateHelper(url, restTemplate); for (VariantWithSamplesAndAnnotation variant : variants) { for (ConsequenceType consequenceType : variant.getAnnotation().getConsequenceTypes()) { if (consequenceType.getProteinSubstitutionScores().size() > 0) { assertNull(consequenceType.getSift()); assertNull(consequenceType.getPolyphen()); } } } }

Target:
public void testProteinSubstitutionScoresModel() { String testVariantId = "rs370478"; String url = "/v1/variants/" + testVariantId + "/info?species=mmusculus_grcm38"; JSONObject jsonObject = WSTestHelpers.testRestTemplateHelperJsonObject(url, restTemplate); JSONArray responseArray = jsonObject.getJSONArray("response"); for (int i = 0; i < responseArray.length(); ++i) { JSONObject response = responseArray.getJSONObject(i); JSONArray resultArray = response.getJSONArray("result"); for (int j = 0; j < resultArray.length(); ++j) { JSONObject result = resultArray.getJSONObject(j); JSONArray consequenceTypes = result.getJSONObject("annotation").getJSONArray("consequenceTypes"); for (int k = 0; k < consequenceTypes.length(); ++k) { JSONObject consequenceType = consequenceTypes.getJSONObject(k); if (!consequenceType.has("ensemblTranscriptId")){ continue; } if (consequenceType.getString("ensemblTranscriptId").equals("ENST00000426146")) { assertTrue(consequenceType.has("proteinSubstitutionScores")); assertFalse(consequenceType.has("sift")); assertFalse(consequenceType.has("polyphen")); } } } } }
Source:
public void schedule(Server server) { ServerCommand serverCommand = new ServerCommand(server, queryExecutorRepository, resultProcessor); long runPeriod = serverCommand.getRunPeriodSeconds(configuration.getRunPeriod()); ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(serverCommand, runPeriod, runPeriod, TimeUnit.SECONDS); serverCommand.setScheduledFuture(scheduledFuture); this.scheduledServerCommands.add(serverCommand); log.debug("Scheduled job for server {}", serverCommand.getName()); }

Target:
public void schedule(Server server) { ServerCommand serverCommand = new ServerCommand(server, queryExecutorRepository, resultProcessor); long runPeriod = serverCommand.getRunPeriodSeconds(configuration.getRunPeriod()); ScheduledFuture<?> scheduledFuture = scheduledExecutor.scheduleAtFixedRate(serverCommand, runPeriod, runPeriod, TimeUnit.SECONDS); synchronized (this.scheduledServerCommands) { this.scheduledServerCommands.add(new ScheduledServerCommand(serverCommand, scheduledFuture)); } log.debug("Scheduled job for server {}", serverCommand.getName()); }
Source:
public void forTypeMirror_typeVariable() { List<? extends TypeParameterElement> typeVariables = getElement(Parameterized.class).getTypeParameters(); assert_().that(TypeNames.forTypeMirror(typeVariables.get(0).asType())) .isEqualTo(TypeVariableName.named("Simple")); assert_().that(TypeNames.forTypeMirror(typeVariables.get(1).asType())) .isEqualTo(new TypeVariableName("ExtendsClass", ImmutableList.<TypeName>of( ClassName.fromClass(Number.class)))); assert_().that(TypeNames.forTypeMirror(typeVariables.get(2).asType())) .isEqualTo(new TypeVariableName("ExtendsInterface", ImmutableList.<TypeName>of( ClassName.fromClass(Runnable.class)))); assert_().that(TypeNames.forTypeMirror(typeVariables.get(3).asType())) .isEqualTo(new TypeVariableName("ExtendsTypeVariable", ImmutableList.<TypeName>of( TypeVariableName.named("Simple")))); TypeName intersectionExpected; if (Double.parseDouble(System.getProperty("java.version").substring(0, 3)) >= 1.8) { intersectionExpected = new TypeVariableName("Intersection", ImmutableList.<TypeName>of( new IntersectionTypeName(ImmutableList.<TypeName>of(ClassName.fromClass(Number.class), ClassName.fromClass(Runnable.class))))); } else { intersectionExpected = new TypeVariableName("Intersection", ImmutableList.<TypeName>of( ClassName.fromClass(Number.class), ClassName.fromClass(Runnable.class))); } assert_().that(TypeNames.forTypeMirror(typeVariables.get(4).asType())) .isEqualTo(intersectionExpected); }

Target:
public void forTypeMirror_typeVariable() { List<? extends TypeParameterElement> typeVariables = getElement(Parameterized.class).getTypeParameters(); assert_().that(TypeNames.forTypeMirror(typeVariables.get(0).asType())) .isEqualTo(TypeVariableName.named("Simple")); assert_().that(TypeNames.forTypeMirror(typeVariables.get(1).asType())) .isEqualTo(new TypeVariableName("ExtendsClass", ImmutableList.<TypeName>of( ClassName.fromClass(Number.class)))); assert_().that(TypeNames.forTypeMirror(typeVariables.get(2).asType())) .isEqualTo(new TypeVariableName("ExtendsInterface", ImmutableList.<TypeName>of( ClassName.fromClass(Runnable.class)))); assert_().that(TypeNames.forTypeMirror(typeVariables.get(3).asType())) .isEqualTo(new TypeVariableName("ExtendsTypeVariable", ImmutableList.<TypeName>of( TypeVariableName.named("Simple")))); }
Source:
private void updateClientsForDevice(@Nullable IDevice device) { if (device == null) { myClientsListModel.clear(); return; } Object selectedObject = myClientsList.getSelectedValue(); Client[] clients = device.getClients(); try { myClientsListUpdateInProgress = ArrayUtil.contains(selectedObject, clients); myClientsListModel.clear(); myClientsListModel.addAll(clients); myClientsList.setSelectedValue(selectedObject, true); } finally { myClientsListUpdateInProgress = false; } }

Target:
private void updateClientsForDevice(@Nullable IDevice device) { if (device == null) { myClientsListModel.clear(); return; } Object selectedObject = myClientsList.getSelectedValue(); Client[] clients = device.getClients(); try { myIgnoreListeners = ArrayUtil.contains(selectedObject, clients); myClientsListModel.clear(); myClientsListModel.addAll(clients); myClientsList.setSelectedValue(selectedObject, true); } finally { myIgnoreListeners = false; } }
Source:
public void onSelectPage(@NonNull HistoryEntry entry) { Intent intent = new Intent(MainActivity.ACTION_PAGE_FOR_TITLE) .setClass(getActivity(), MainActivity.class) .putExtra(MainActivity.EXTRA_HISTORYENTRY, entry) .putExtra(MainActivity.EXTRA_PAGETITLE, entry.getTitle()); startActivity(intent); }

Target:
public void onSelectPage(@NonNull HistoryEntry entry) { startActivity(MainActivity.newIntent(getContext(), entry, entry.getTitle())); }
Source:
public void getNotModifiedBlobAndVerify(String blobId) throws Exception { JSONObject headers = new JSONObject(); SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.US); Date date = new Date(System.currentTimeMillis()); String dateStr = dateFormat.format(date); headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr); RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getResponseStatus()); assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null); assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified")); assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE)); assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE)); assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length); }

Target:
public void getNotModifiedBlobAndVerify(String blobId) throws Exception { JSONObject headers = new JSONObject(); SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(System.currentTimeMillis()); String dateStr = dateFormat.format(date); headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr); RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getResponseStatus()); assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null); assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified")); assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE)); assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE)); assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length); }
Source:
public void start() { try { LOGGER.info("Starting Redis Channel: " + getName()); redisOperator = RedisInit.getInstance(redisConf, jedisPoolConfig); counter.start(); super.start(); } catch (Exception e) { LOGGER.error("Could not start Redis Chnnel"); throw new FlumeException("Unable to create Redis Connections. " + "Check whether Redis Server are up and that the " + "Flume agent can connect to it.", e); } }

Target:
public void start() { try { LOGGER.info("Starting Redis Channel: " + getName()); redisOperator = RedisInit.getInstance(redisConf, jedisPoolConfig); counter.start(); super.start(); } catch (CannotGetRedisInstanceException e) { LOGGER.error("Could not start Redis Chnnel"); throw new FlumeException("Unable to create Redis Connections. " + "Check whether Redis Server are up and that the " + "Flume agent can connect to it.", e); } catch (UnsupportRedisTypeException e) { LOGGER.error("Could not start Redis Chnnel"); throw new FlumeException("Unable to create Redis Connections. " + "Check whether Redis Type is correct.", e); } }
Source:
public void dispatchOutput(String output, boolean detectLocalEcho) { if (detectLocalEcho && !localEcho_.isEmpty()) { String lastOutput = ""; while (!localEcho_.isEmpty() && lastOutput.length() < output.length()) { lastOutput += localEcho_.poll(); } if (lastOutput.equals(output)) { return; } lastOutput += " \r"; if (lastOutput.equals(output)) { return; } localEcho_.clear(); } xterm_.write(output); }

Target:
public void dispatchOutput(String output, boolean detectLocalEcho) { if (detectLocalEcho && !localEcho_.isEmpty()) { String lastOutput = ""; while (!localEcho_.isEmpty() && lastOutput.length() < output.length()) { lastOutput += localEcho_.poll(); } if (lastOutput.equals(output)) { return; } if (output.startsWith(lastOutput)) { xterm_.write(output.substring(lastOutput.length())); return; } localEcho_.clear(); } xterm_.write(output); }
Source:
public List<String> getInvalidityInfo() { FieldValidator validator = new FieldValidator(); List<String> errors = new ArrayList<>(); addNonEmptyError(validator.getInvalidityInfoForGoogleId(googleId), errors); if (!StringHelper.isEmpty(shortName)) { addNonEmptyError(validator.getInvalidityInfoForPersonName(shortName), errors); } if (!StringHelper.isEmpty(email)) { addNonEmptyError(validator.getInvalidityInfoForEmail(email), errors); } if (!StringHelper.isEmpty(institute)) { addNonEmptyError(validator.getInvalidityInfoForInstituteName(institute), errors); } if (!StringHelper.isEmpty(nationality)) { addNonEmptyError(validator.getInvalidityInfoForNationality(nationality), errors); } Assumption.assertNotNull(this.pictureKey); return errors; }

Target:
public List<String> getInvalidityInfo() { FieldValidator validator = new FieldValidator(); List<String> errors = new ArrayList<>(); addNonEmptyError(validator.getInvalidityInfoForGoogleId(googleId), errors); if (!StringHelper.isEmpty(shortName)) { addNonEmptyError(validator.getInvalidityInfoForPersonName(shortName), errors); } if (!StringHelper.isEmpty(email)) { addNonEmptyError(validator.getInvalidityInfoForEmail(email), errors); } if (!StringHelper.isEmpty(institute)) { addNonEmptyError(validator.getInvalidityInfoForInstituteName(institute), errors); } if (!StringHelper.isEmpty(nationality)) { addNonEmptyError(validator.getInvalidityInfoForNationality(nationality), errors); } Assumption.assertNotNull(gender); Assumption.assertNotNull(this.pictureKey); return errors; }
Source:
private SocketAddress nextServer(Set<SocketAddress> failedServers) { SocketAddress server; if (balancer instanceof FailoverRequestBalancingStrategy) { server = ((FailoverRequestBalancingStrategy) balancer).nextServer(failedServers); } else { server = balancer.nextServer(); } return server; }

Target:
private SocketAddress nextServer(Set<SocketAddress> failedServers) { return balancer.nextServer(failedServers); }
Source:
public synchronized Connection add(Connection connection) { if (!maps.containsKey(connection.channel().id())) { maps.put(connection.channel().id(), connection); connections.add(connection); } return connection; }

Target:
public Connection add(Connection connection) { Connection conn = connections.putIfAbsent(connection.channel().id(), connection); if (conn != null) { return conn; } return connection; }
Source:
private JCheckBox createCheckBox(String label, boolean selected) { JCheckBox checkBox = new JCheckBox(label, selected); checkBox.setOpaque(false); checkBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); return checkBox; }

Target:
private JCheckBox createCheckBox(String label, boolean selected) { final JCheckBox checkBox = new JCheckBox(label, selected); checkBox.setOpaque(false); checkBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); checkBox.addItemListener(item -> onSettingsUpdated(false)); return checkBox; }
Source:
public RemotingConnectorService(String resolvedDomain, String expressionsDomain) { this.resolvedDomain = resolvedDomain; this.expressionsDomain = expressionsDomain; }

Target:
private RemotingConnectorService(String resolvedDomain, String expressionsDomain) { this.resolvedDomain = resolvedDomain; this.expressionsDomain = expressionsDomain; }
Source:
public static void uploadFileIfPossible(ServerSideEncryptingAmazonS3 service, boolean disableAcl, String bucket, String key, File file) { final PutObjectRequest logFilePutRequest = new PutObjectRequest(bucket, key, file); if (!disableAcl) { logFilePutRequest.setAccessControlList(S3Utils.grantFullControlToBucketOwner(service, bucket)); } log.info("Pushing [%s] to bucket[%s] and key[%s].", file, bucket, key); service.putObject(logFilePutRequest); }

Target:
public static void uploadFileIfPossible(ServerSideEncryptingAmazonS3 service, boolean disableAcl, String bucket, String key, File file) { final PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file); if (!disableAcl) { putObjectRequest.setAccessControlList(S3Utils.grantFullControlToBucketOwner(service, bucket)); } log.info("Pushing [%s] to bucket[%s] and key[%s].", file, bucket, key); service.putObject(putObjectRequest); }
Source:
public InjectedCommandGroup(CommandGroupBase previous) { super(); this.previous = previous; }

Target:
public InjectedCommandGroup(CommandGroupBase previous) { this("InjectedCommandGroup", previous); }
Source:
private void sortByHilbertIndex(T[] items) { if (items.length < degree) { return; } Rectangle bounds = items[0].getExtent(); for (int i = 1; i < items.length; i++) { bounds = bounds.merge(items[i].getExtent()); } HilbertIndex hilbert = new HilbertIndex(bounds); Arrays.parallelSort(items, Comparator.comparing((HasExtent item) -> hilbert.index( (item.getExtent().getXMin() + item.getExtent().getXMax()) / 2, (item.getExtent().getYMin() + item.getExtent().getYMax()) / 2))); }

Target:
private void sortByHilbertIndex(T[] items) { if (items == null || items.length < 2) { return; } Rectangle totalExtent = items[0].getExtent(); for (int i = 1; i < items.length; i++) { totalExtent = totalExtent.merge(items[i].getExtent()); } HilbertIndex hilbert = new HilbertIndex(totalExtent); Arrays.parallelSort(items, Comparator.comparing(item -> hilbert.indexOf( (item.getExtent().getXMin() + item.getExtent().getXMax()) / 2, (item.getExtent().getYMin() + item.getExtent().getYMax()) / 2))); }
Source:
protected void modifyTable(HTableDescriptor descriptor) throws IOException { try(Admin admin = getConnection().getAdmin()) { admin.modifyTable(descriptor); } }

Target:
protected void modifyTable(HTableDescriptor descriptor) throws IOException { try(Admin admin = getConnection().getAdmin()) { admin.modifyTable((TableDescriptor)descriptor); } }
Source:
public void setCurrentFieldForTest(Method method) { try { setFieldsForTest(method.getName()); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } }

Target:
public void setCurrentFieldForTest(Method method) throws IOException, URISyntaxException { setFieldsForTest(method.getName()); }
Source:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("loading was interrupted."); } } }

Target:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); } }
Source:
LocalDate selectBaseDate(SchedulePeriod period) { switch (this) { case PERIOD_END: return period.getEndDate(); case PERIOD_START: default: return period.getStartDate(); } }

Target:
LocalDate selectBaseDate(SchedulePeriod period) { return (this == PERIOD_END ? period.getEndDate() : period.getStartDate()); }
Source:
public void addMoodListener(MoodListener listener) { moodListeners.add(listener); }

Target:
public synchronized void addMoodListener(MoodListener listener) { moodListeners.add(listener); }
Source:
public boolean isSameHour(Date d1, Date d2) { Calendar c1 = Calendar.getInstance(tz); c1.setTime(d1); Calendar c2 = Calendar.getInstance(tz); c2.setTime(d2); return isSameDay(d1, d2) && c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY); }

Target:
public boolean isSameHour(Date d1, Date d2) { Calendar c1 = Calendar.getInstance(tz); c1.setTime(d1); Calendar c2 = Calendar.getInstance(tz); c2.setTime(d2); return isSameHour(c1, c2); }
Source:
public Optional<String> getContainerIdIfContainerized() throws IOException, InterruptedException { ByteArrayOutputStream cgroup = new ByteArrayOutputStream(); launcher.launch().cmds("cat", "/proc/self/cgroup").quiet(true).stdout(cgroup).join(); final Pattern pattern = Pattern.compile("(?m)^\\d+:\\w+:/docker/(?<containerId>\\p{XDigit}{12,})$"); final String charsetName = Charset.defaultCharset().name(); Matcher matcher = pattern.matcher(cgroup.toString(charsetName)); return matcher.find() ? Optional.of(matcher.group("containerId")) : Optional.<String>absent(); }

Target:
public Optional<String> getContainerIdIfContainerized() throws IOException, InterruptedException { final Pattern pattern = Pattern.compile("(?m)^\\d+:\\w+:/docker/(?<containerId>\\p{XDigit}{12,})$"); String cgroup = node.createPath("/proc/self/cgroup").readToString(); Matcher matcher = pattern.matcher(cgroup); return matcher.find() ? Optional.of(matcher.group(1)) : Optional.<String>absent(); }
Source:
public void createElement() { when(service.getDateTime()).thenReturn(TIMESTAMP); AppConfigElement element = TestUtils.getAppConfigElement(); element.setRevision(null); element.setDeleted(true); when(dao.saveElementRevision(element)).thenReturn(VERSION_HOLDER); VersionHolder returned = service.createElement(TEST_STUDY, element); assertEquals(VERSION_HOLDER, returned); verify(dao).saveElementRevision(elementCaptor.capture()); assertEquals(new Long(1), elementCaptor.getValue().getRevision()); AppConfigElement captured = elementCaptor.getValue(); assertNull(captured.getVersion()); assertFalse(captured.isDeleted()); assertEquals("api", captured.getStudyId()); assertEquals("api:id", captured.getKey()); assertEquals(TIMESTAMP.getMillis(), captured.getCreatedOn()); assertEquals(TIMESTAMP.getMillis(), captured.getModifiedOn()); }

Target:
public void createElement() { AppConfigElement element = TestUtils.getAppConfigElement(); element.setRevision(null); element.setDeleted(true); when(dao.saveElementRevision(element)).thenReturn(VERSION_HOLDER); VersionHolder returned = service.createElement(TEST_STUDY, element); assertEquals(VERSION_HOLDER, returned); verify(dao).saveElementRevision(elementCaptor.capture()); assertEquals(new Long(1), elementCaptor.getValue().getRevision()); AppConfigElement captured = elementCaptor.getValue(); assertNull(captured.getVersion()); assertFalse(captured.isDeleted()); assertEquals("api", captured.getStudyId()); assertEquals("api:id", captured.getKey()); assertEquals(TIMESTAMP.getMillis(), captured.getCreatedOn()); assertEquals(TIMESTAMP.getMillis(), captured.getModifiedOn()); }
Source:
public static void validatePrimaryKey(TableSchema schema) { schema.getPrimaryKey().ifPresent( key -> { List<LogicalTypeRoot> illegalTypes = key.getColumns() .stream() .map(fieldName -> { LogicalType logicalType = schema.getFieldDataType(fieldName).get().getLogicalType(); if (hasRoot(logicalType, LogicalTypeRoot.DISTINCT_TYPE)) { return ((DistinctType) logicalType).getSourceType().getTypeRoot(); } else { return logicalType.getTypeRoot(); } }) .filter(ILLEGAL_PRIMARY_KEY_TYPES::contains) .collect(Collectors.toList()); if (!illegalTypes.isEmpty()) { throw new ValidationException( String.format( "The table has a primary key on columns of illegal types: %s.\n" + " Elasticsearch sink does not support primary keys on columns of types: %s.", ILLEGAL_PRIMARY_KEY_TYPES, illegalTypes)); } } ); }

Target:
public static void validatePrimaryKey(TableSchema schema) { schema.getPrimaryKey().ifPresent( key -> { List<LogicalTypeRoot> illegalTypes = key.getColumns() .stream() .map(fieldName -> { LogicalType logicalType = schema.getFieldDataType(fieldName).get().getLogicalType(); if (hasRoot(logicalType, LogicalTypeRoot.DISTINCT_TYPE)) { return ((DistinctType) logicalType).getSourceType().getTypeRoot(); } else { return logicalType.getTypeRoot(); } }) .filter(ILLEGAL_PRIMARY_KEY_TYPES::contains) .collect(Collectors.toList()); if (!illegalTypes.isEmpty()) { throw new ValidationException( String.format( "The table has a primary key on columns of illegal types: %s.\n" + " Elasticsearch sink does not support primary keys on columns of types: %s.", illegalTypes, ILLEGAL_PRIMARY_KEY_TYPES)); } } ); }
Source:
private void setStaffOnly(Resource resc, Model model) { Map<String, String> depositStatus = getDepositStatus(); String staffOnly = depositStatus.get(DepositField.staffOnly.name()); if (Boolean.parseBoolean(staffOnly)) { model.add(resc, CdrAcl.none, PUBLIC_PRINC); model.add(resc, CdrAcl.none, AUTHENTICATED_PRINC); } }

Target:
private void setStaffOnly(Resource resc, Model model) { model.add(resc, CdrAcl.none, PUBLIC_PRINC); model.add(resc, CdrAcl.none, AUTHENTICATED_PRINC); }
Source:
public void stop(BundleContext bundleContext) throws Exception { EMFCompareRCPPlugin.plugin = null; final IExtensionRegistry registry = Platform.getExtensionRegistry(); registry.removeListener(loadOnDemandRegistryListener); loadOnDemandRegistryListener = null; loadOnDemandRegistry = null; registry.removeListener(postProcessorFactoryRegistryListener); postProcessorFactoryRegistryListener = null; postProcessorDescriptorsRegistry = null; registry.removeListener(mergerRegistryListener); mergerRegistryListener = null; mergerRegistry = null; registry.removeListener(matchEngineRegistryListener); matchEngineRegistryListener = null; matchEngineFactoryRegistry = null; registry.removeListener(adapterFactoryRegistryListener); adapterFactoryRegistryListener = null; adapterFactoryRegistry = null; registry.removeListener(diffEngineListener); diffEngineListener = null; diffEngineRegistry = null; registry.removeListener(equiEngineListener); equiEngineListener = null; equiEngineRegistry = null; registry.removeListener(conflictDetectorListener); conflictDetectorListener = null; conflictDetectorRegistry = null; registry.removeListener(reqEngineListener); reqEngineListener = null; reqEngineRegistry = null; super.stop(bundleContext); }

Target:
public void stop(BundleContext bundleContext) throws Exception { EMFCompareRCPPlugin.plugin = null; final IExtensionRegistry registry = Platform.getExtensionRegistry(); discardConflictDetectorRegistry(registry); discardReqEngineRegistry(registry); discardEquiEngineRegistry(registry); discardDiffEngineRegistry(registry); discardLoadOnDemandeRegistry(registry); discardPostProcessorfactoryRegistry(registry); discardMergerRegistry(registry); discardMatchEngineRegistry(registry); discardAdapterFactoryRegistry(registry); super.stop(bundleContext); }
Source:
public void setRef(String ref) { mRef = ref; getArguments().putString("ref", ref); mSubscriptions[0] = mLoadReadme.compose(RxTools.applySchedulers()).subscribe(); if (mContentView != null) { mContentView.findViewById(R.id.readme).setVisibility(View.GONE); mContentView.findViewById(R.id.pb_readme).setVisibility(View.VISIBLE); } }

Target:
public void setRef(String ref) { mRef = ref; getArguments().putString("ref", ref); loadReadme(false); if (mContentView != null) { mContentView.findViewById(R.id.readme).setVisibility(View.GONE); mContentView.findViewById(R.id.pb_readme).setVisibility(View.VISIBLE); } }
Source:
private void reload() throws IOException { final Reader r = new FileReader(ConfigFileConstants.getFile(ConfigFileConstants.EVENTD_CONFIG_FILE_NAME)); m_config = JaxbUtils.unmarshal(EventdConfiguration.class, r); }

Target:
private void reload() throws IOException { try (final Reader r = new FileReader(ConfigFileConstants.getFile(ConfigFileConstants.EVENTD_CONFIG_FILE_NAME))) { m_config = JaxbUtils.unmarshal(EventdConfiguration.class, r); } }
Source:
public void onResponse(Response coapResponse) { LOG.debug("Received coap response: for {}", coapResponse, coapRequest); coapRequest.removeMessageObserver(this); if (evenRaised.compareAndSet(false, true)) { cleaningTask.cancel(false); responseCallback.onResponse(coapResponse); } else { LOG.warn("OnResponse callback ignored because an event was already raised for this request {}", coapRequest); } }

Target:
public void onResponse(Response coapResponse) { LOG.debug("Received coap response: for {}", coapResponse, coapRequest); coapRequest.removeMessageObserver(this); if (eventRaised.compareAndSet(false, true)) { cleaningTask.cancel(false); try { responseCallback.onResponse(coapResponse); } catch (RuntimeException e) { LOG.warn("Uncaught exception during onResponse callback"); } } else { LOG.debug("OnResponse callback ignored because an event was already raised for this request {}", coapRequest); } }
Source:
public void handlePageSelected() { assertThat(activity.pageSelectedViewPager).isNull(); assertThat(activity.pageSelectedPosition).isEqualTo(0); ViewPager.OnPageChangeListener listener = field("mOnPageChangeListener").ofType(ViewPager.OnPageChangeListener.class).in(viewPager).get(); int position = 100; listener.onPageSelected(position); assertThat(activity.pageSelectedViewPager).isEqualTo(viewPager); assertThat(activity.pageSelectedPosition).isEqualTo(position); }

Target:
public void handlePageSelected() { initViewPager(R.id.viewPager1); assertViewPagerIsNull(); assertPositionIsNotSet(); int position = 100; listener.onPageSelected(position); assertThat(activity.viewPager).isEqualTo(viewPager); assertThat(activity.position).isEqualTo(position); }