auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testSchemaHandling() throws Exception { Schema inputSchema = Schema.recordOf("sourceRecord", Schema.Field.of(ID, Schema.of(Schema.Type.STRING)), Schema.Field.of(NAME, Schema.of(Schema.Type.STRING)), Schema.Field.of(SALARY, Schema.of(Schema.Type.STRING)), Schema.Field.of(DESIGNATIONID, Schema.unionOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.NULL)))); ValueMapper.Config config = new ValueMapper.Config("designationid:designation_lookup_table:designationName", "designationid:DEFAULTID"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(inputSchema); new ValueMapper(config).configurePipeline(configurer); Schema outputSchema = configurer.getOutputSchema(); Assert.assertEquals(Schema.of(Schema.Type.STRING).getType(), outputSchema.getField(DESIGNATIONNAME).getSchema().getType()); Assert.assertEquals(Schema.of(Schema.Type.STRING).getType(), outputSchema.getField(SALARY).getSchema().getType()); }

Target:
public void testSchemaHandling() throws Exception { Schema inputSchema = Schema.recordOf("sourceRecord", Schema.Field.of(ID, Schema.of(Schema.Type.STRING)), Schema.Field.of(NAME, Schema.of(Schema.Type.STRING)), Schema.Field.of(SALARY, Schema.of(Schema.Type.STRING)), Schema.Field.of(DESIGNATIONID, Schema.nullableOf(Schema.of(Schema.Type.STRING)))); ValueMapper.Config config = new ValueMapper.Config("designationid:designation_lookup_table:designationName", "designationid:DEFAULTID"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(inputSchema); new ValueMapper(config).configurePipeline(configurer); Schema outputSchema = configurer.getOutputSchema(); Schema expectedOutputSchema = Schema.recordOf("sourceRecord.formatted", Schema.Field.of(ID, Schema.of(Schema.Type.STRING)), Schema.Field.of(NAME, Schema.of(Schema.Type.STRING)), Schema.Field.of(SALARY, Schema.of(Schema.Type.STRING)), Schema.Field.of(DESIGNATIONNAME, Schema.of(Schema.Type.STRING))); Assert.assertEquals(expectedOutputSchema, outputSchema); }
Source:
public void createDestination(Datastream datastream) { }

Target:
public void createDestination(Datastream datastream) { throw new UnsupportedOperationException("Create destination is not supported for event hub."); }
Source:
private ResultScanner<Row> streamRows(ReadRowsRequest request) { expandPoolIfNecessary(this.bigtableOptions.getChannelCount()); ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = channelPool.newCall(BigtableGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); ResponseQueueReader<Row> responseQueueReader = new ResponseQueueReader<>( retryOptions.getReadPartialRowTimeoutMillis(), retryOptions.getStreamingBufferSize()); StreamObserver<ReadRowsResponse> rowMerger = new RowMerger(responseQueueReader); ClientCall.Listener<ReadRowsResponse> listener = new StreamObserverAdapter<>(readRowsCall, rowMerger); asyncUtilities.asyncServerStreamingCall(readRowsCall, request, listener); if (request.getRows().getRowKeysCount() > 1 || request.getRows().getRowRangesCount() > 0) { readRowsCall.request(4); } CancellationToken cancellationToken = createCancellationToken(readRowsCall); return new StreamingBigtableResultScanner(responseQueueReader, cancellationToken); }

Target:
private ResultScanner<Row> streamRows(ReadRowsRequest request) { expandPoolIfNecessary(this.bigtableOptions.getChannelCount()); ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = channelPool.newCall(BigtableGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); ResponseQueueReader<Row> responseQueueReader = new ResponseQueueReader<>( retryOptions.getReadPartialRowTimeoutMillis(), retryOptions.getStreamingBufferSize()); StreamObserver<ReadRowsResponse> rowMerger = new RowMerger(responseQueueReader); ClientCall.Listener<ReadRowsResponse> listener = new StreamObserverAdapter<>(readRowsCall, rowMerger); asyncUtilities.asyncServerStreamingCall(readRowsCall, request, listener); CancellationToken cancellationToken = createCancellationToken(readRowsCall); return new StreamingBigtableResultScanner(responseQueueReader, cancellationToken); }
Source:
public void testRemapMissingDependencies() { String UUID = "uuid"; String NAME = "name"; String PAGE = "page"; DataSetDef def1 = new DataSetDef(); def1.setUUID(UUID); def1.setName(NAME); HashMap<String, List<String>> validation = new HashMap<>(); validation.put(PAGE, Collections.singletonList(UUID)); ExportInfo assets = new ExportInfo(Collections.singletonList(def1), Collections.emptyList(), false); exportWizardSummaryPage.setExportInfo(assets); exportWizardSummaryPage.remapMissingDependencies(validation); assertEquals(NAME, validation.get(PAGE).get(0)); }

Target:
public void testRemapMissingDependencies() { String UUID = "uuid"; String NAME = "name"; String PAGE = "page"; DataSetDef def1 = new DataSetDef(); def1.setUUID(UUID); def1.setName(NAME); HashMap<String, List<String>> validation = new HashMap<>(); validation.put(PAGE, Collections.singletonList(UUID)); ExportInfo exportInfo = new ExportInfo(Collections.singletonList(def1), Collections.emptyList(), false); exportWizardSummaryPage.setExportInfo(exportInfo); exportWizardSummaryPage.remapMissingDependencies(validation); assertEquals(NAME, validation.get(PAGE).get(0)); }
Source:
private CompletableFuture<List<LogEntry>> fetchLogEntries() { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(5000l); } catch (InterruptedException e) { e.printStackTrace(); } List<LogEntry> result = new ArrayList<>(); LogSession lastLogSession = LogReader.parseLogFile(this.fInputFile, getLogMaxTailSize(), result, this.fMemento); if (lastLogSession != null && (lastLogSession.getDate() == null || isEclipseStartTime(lastLogSession.getDate()))) { currentSession = lastLogSession; } else { currentSession = null; } return result; }); }

Target:
private CompletableFuture<List<LogEntry>> fetchLogEntries() { return CompletableFuture.supplyAsync(() -> { List<LogEntry> result = new ArrayList<>(); LogSession lastLogSession = LogReader.parseLogFile(this.fInputFile, getLogMaxTailSize(), result, this.fMemento); if (lastLogSession != null && (lastLogSession.getDate() == null || isEclipseStartTime(lastLogSession.getDate()))) { currentSession = lastLogSession; } else { currentSession = null; } return result; }); }
Source:
public void synchronizeToLocalDirectory(File localDirectory, String bucketName, String remoteFolder) { if(!lock.tryLock()) { if(logger.isInfoEnabled()) { logger.info("Sync already in progess"); } return; } if(logger.isInfoEnabled()) { logger.info("Starting sync with local directory"); } try { if(remoteFolder != null && "/".equals(remoteFolder)) { remoteFolder = null; } if(filter instanceof AbstractFileNameFilter) { ((AbstractFileNameFilter)filter).setFolderName(remoteFolder); } String nextMarker = null; do { PaginatedObjectsView paginatedView = client.listObjects(bucketName, remoteFolder,nextMarker,maxObjectsPerBatch); if(paginatedView == null) break; nextMarker = paginatedView.getNextMarker(); List<S3ObjectSummary> summaries = paginatedView.getObjectSummary(); for(S3ObjectSummary summary:summaries) { String key = summary.getKey(); if(key.endsWith("/")) { continue; } if(!filter.accept(key)) continue; AmazonS3Object s3Object = null; try { s3Object = client.getObject(bucketName, "/", key); synchronizeObjectWithFile(localDirectory,summary,s3Object); } finally { if(s3Object.getInputStream() != null) { s3Object.getInputStream().close(); } } } } while(nextMarker != null); } catch (IOException e) { logger.error("Caught Exception while trying to close s3object InputStream", e); } finally { lock.unlock(); if(logger.isInfoEnabled()) { logger.info("Sync completed"); } } }

Target:
public void synchronizeToLocalDirectory(File localDirectory, String bucketName, String remoteFolder) { if(!lock.tryLock()) { if(logger.isInfoEnabled()) { logger.info("Sync already in progess"); } return; } if(logger.isInfoEnabled()) { logger.info("Starting sync with local directory"); } try { if(remoteFolder != null && "/".equals(remoteFolder)) { remoteFolder = null; } if(filter instanceof AbstractFileNameFilter) { ((AbstractFileNameFilter)filter).setFolderName(remoteFolder); } String nextMarker = null; do { PaginatedObjectsView paginatedView = client.listObjects(bucketName, remoteFolder,nextMarker,maxObjectsPerBatch); if(paginatedView == null) break; nextMarker = paginatedView.getNextMarker(); List<S3ObjectSummary> summaries = paginatedView.getObjectSummary(); for(S3ObjectSummary summary:summaries) { String key = summary.getKey(); if(key.endsWith("/")) { continue; } if(!filter.accept(key)) continue; AmazonS3Object s3Object = null; try { s3Object = client.getObject(bucketName, "/", key); synchronizeObjectWithFile(localDirectory,summary,s3Object); } finally { if(s3Object != null && s3Object.getInputStream() != null) { s3Object.getInputStream().close(); } } } } while(nextMarker != null); } catch (IOException e) { logger.error("Caught Exception while trying to close s3object InputStream", e); } finally { lock.unlock(); if(logger.isInfoEnabled()) { logger.info("Sync completed"); } } }
Source:
public VmGuestInfoModel() { super(); setTitle(ConstantsManager.getInstance().getConstants().sessionsTitle()); setHelpTag(HelpTag.guest_info); setHashName("guest_info"); guestOsType = OsType.Other; guestOsArch = ArchitectureType.undefined; guestOsCodename = ""; guestOsDistribution = ""; guestOsKernelVersion = ""; guestOsVersion = ""; guestOs = ""; guestOsTimezoneName = ""; guestOsTimezoneOffset = 0; guestOsNamedVersion = ""; guestOsTimezone = ""; }

Target:
public VmGuestInfoModel() { setTitle(ConstantsManager.getInstance().getConstants().guestInformationTitle()); setHelpTag(HelpTag.guest_info); setHashName("guest_info"); guestOsType = OsType.Other; guestOsArch = ArchitectureType.undefined; guestOsCodename = ""; guestOsDistribution = ""; guestOsKernelVersion = ""; guestOsVersion = ""; guestOs = ""; guestOsTimezoneName = ""; guestOsTimezoneOffset = 0; guestOsNamedVersion = ""; guestOsTimezone = ""; }
Source:
public MethodBehavior execute(MethodTree methodTree) { try { Symbol.MethodSymbol methodSymbol = methodTree.symbol(); ExplodedGraphWalker walker = egwFactory.createWalker(behaviorCache, (SemanticModel) context.getSemanticModel()); if (methodCanNotBeOverriden(methodSymbol)) { MethodBehavior methodBehavior = new MethodBehavior(methodSymbol); behaviorCache.add(methodSymbol, methodBehavior); methodBehavior = walker.visitMethod(methodTree, methodBehavior); methodBehavior.completed(); return methodBehavior; } else { return walker.visitMethod(methodTree); } } catch (ExplodedGraphWalker.MaximumStepsReachedException | ExplodedGraphWalker.ExplodedGraphTooBigException | TransitiveRelationExceededException exception) { LOG.debug("Could not complete symbolic execution: ", exception); } return null; }

Target:
public MethodBehavior execute(MethodTree methodTree) { try { Symbol.MethodSymbol methodSymbol = methodTree.symbol(); ExplodedGraphWalker walker = egwFactory.createWalker(behaviorCache, (SemanticModel) context.getSemanticModel()); if (methodCanNotBeOverriden(methodSymbol)) { MethodBehavior methodBehavior = new MethodBehavior(methodSymbol); behaviorCache.add(methodSymbol, methodBehavior); methodBehavior = walker.visitMethod(methodTree, methodBehavior); methodBehavior.completed(); return methodBehavior; } else { return walker.visitMethod(methodTree); } } catch (ExplodedGraphWalker.MaximumStepsReachedException | ExplodedGraphWalker.ExplodedGraphTooBigException | RelationalSymbolicValue.TransitiveRelationExceededException exception) { LOG.debug("Could not complete symbolic execution: ", exception); } return null; }
Source:
static Set<Type> getMajorPermissions() { final Set<Type> majorTypes = new HashSet<>(); for (final Type type : Type.values()) { if (type.isMajor()) { majorTypes.add(type); } } return majorTypes; }

Target:
static Set<Type> getMajorPermissions() { final Set<Type> majorTypes = EnumSet.noneOf(Type.class); for (final Type type : Type.values()) { if (type.isMajor()) { majorTypes.add(type); } } return majorTypes; }
Source:
private void copyPathOfSelectionToClipboard(final TreeViewer viewer) { Clipboard cb = new Clipboard(viewer.getControl().getDisplay()); TextTransfer t = TextTransfer.getInstance(); String text = getTextFrom( (IStructuredSelection) viewer.getSelection()); if (text == null) { return; } else { cb.setContents(new Object[] { text }, new Transfer[] { t }); } cb.dispose(); }

Target:
private void copyPathOfSelectionToClipboard(final TreeViewer viewer) { Clipboard cb = new Clipboard(viewer.getControl().getDisplay()); TextTransfer t = TextTransfer.getInstance(); String text = getTextFrom( (IStructuredSelection) viewer.getSelection()); try { if (text != null) { cb.setContents(new Object[] { text }, new Transfer[] { t }); } } finally { cb.dispose(); } }
Source:
protected static void assertAccount(Account actualAccount, String expectedType, String expectedSubType, Account.VerificationStatus expectedVerificationStatus, Double expectedBalanceAvailable, Double expectedBalanceCurrent, Double expectedBalanceLimit, String expectedName, String expectedMask, String expectedOfficialName) { assertNotNull(actualAccount.getAccountId()); assertEquals(expectedType, actualAccount.getType()); assertEquals(expectedSubType, actualAccount.getSubtype()); assertEquals(expectedVerificationStatus, actualAccount.getVerificationStatus()) assertEquals(expectedBalanceAvailable, actualAccount.getBalances().getAvailable()); assertEquals(expectedBalanceCurrent, actualAccount.getBalances().getCurrent()); assertEquals(expectedBalanceLimit, actualAccount.getBalances().getLimit()); assertEquals(expectedName, actualAccount.getName()); assertEquals(expectedMask, actualAccount.getMask()); assertEquals(expectedOfficialName, actualAccount.getOfficialName()); }

Target:
protected static void assertAccount(Account actualAccount, String expectedType, String expectedSubType, Account.VerificationStatus expectedVerificationStatus, Double expectedBalanceAvailable, Double expectedBalanceCurrent, Double expectedBalanceLimit, String expectedName, String expectedMask, String expectedOfficialName) { assertNotNull(actualAccount.getAccountId()); assertEquals(expectedType, actualAccount.getType()); assertEquals(expectedSubType, actualAccount.getSubtype()); assertEquals(expectedVerificationStatus, actualAccount.getVerificationStatus()); assertEquals(expectedBalanceAvailable, actualAccount.getBalances().getAvailable()); assertEquals(expectedBalanceCurrent, actualAccount.getBalances().getCurrent()); assertEquals(expectedBalanceLimit, actualAccount.getBalances().getLimit()); assertEquals(expectedName, actualAccount.getName()); assertEquals(expectedMask, actualAccount.getMask()); assertEquals(expectedOfficialName, actualAccount.getOfficialName()); }
Source:
public Encounter createEncounter(String configName, Encounter encounter) { validateEncounter(encounter); Encounter createdEncounter; Config config = configService.getConfigByName(configName); List<Observation> updatedObs = resolveConceptUuidForConceptNames(config, encounter.getObs()); try { encounter.setObs(updatedObs); createdEncounter = encounterResource.createEncounter(config, encounter); eventRelay.sendEventMessage(new MotechEvent(EventKeys.CREATED_NEW_ENCOUNTER_SUBJECT, EventHelper.encounterParameters(createdEncounter))); } catch (HttpClientErrorException e) { throw new OpenMRSException("Could not create encounter with patient uuid: " + encounter.getPatient().getUuid(), e); } return createdEncounter; }

Target:
public Encounter createEncounter(String configName, Encounter encounter) { validateEncounter(encounter); Encounter createdEncounter; Config config = configService.getConfigByName(configName); try { createdEncounter = encounterResource.createEncounter(config, encounter); eventRelay.sendEventMessage(new MotechEvent(EventKeys.CREATED_NEW_ENCOUNTER_SUBJECT, EventHelper.encounterParameters(createdEncounter))); } catch (HttpClientErrorException e) { throw new OpenMRSException(String.format("Could not create encounter with patient uuid: %s. %s %s", encounter.getPatient().getUuid(), e.getMessage(), e.getResponseBodyAsString()), e); } return createdEncounter; }
Source:
private List<CloudbreakEventV4Response> getLegacyStackType(Stack stack) { List<CloudbreakEventV4Response> events = cloudbreakEventsFacade .retrieveEventsByStack(stack.getId(), StackType.LEGACY, PageRequest.of(0, Integer.MAX_VALUE)).getContent(); if (events.isEmpty()) { LOGGER.info("Cannot find any legacy events for stack: {}, crn: {}", stack.getId(), stack.getResourceCrn()); } else { LOGGER.info("{} egacy events for stack: {}, crn: {}", events.size(), stack.getId(), stack.getResourceCrn()); } return events; }

Target:
private List<CloudbreakEventV4Response> getLegacyStackType(Stack stack) { List<CloudbreakEventV4Response> events = cloudbreakEventsFacade .retrieveEventsByStack(stack.getId(), StackType.LEGACY, PageRequest.of(0, Integer.MAX_VALUE)).getContent(); if (events.isEmpty()) { LOGGER.info("Cannot find any legacy events for stack: {}, crn: {}", stack.getId(), stack.getResourceCrn()); } else { LOGGER.info("{} legacy events for stack: {}, crn: {}", events.size(), stack.getId(), stack.getResourceCrn()); } return events; }
Source:
public boolean hasAttribute(final String tag) { return hasAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag))!=null; }

Target:
public boolean hasAttribute(final String tag) { return getAttribute(tag)!=null; }
Source:
private static boolean shouldSkipInputFileNameCheck(String path, String fileName) { return "package-info.java".equals(fileName) || "package.html".equals(fileName) || path.contains(File.separatorChar + "inputs" + File.separatorChar) || path.contains(File.separatorChar + "translation" + File.separatorChar) || fileName.charAt(0) == '.'; }

Target:
private static boolean shouldSkipInputFileNameCheck(String path, String fileName) { return "package-info.java".equals(fileName) || "package.html".equals(fileName) || path.contains(File.separatorChar + "inputs" + File.separatorChar) || path.contains(File.separatorChar + "translation" + File.separatorChar); }
Source:
private ManagedThreadFactoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.MANAGED_THREAD_FACTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.MANAGED_THREAD_FACTORY)) .setAddHandler(ManagedThreadFactoryAdd.INSTANCE) .setRemoveHandler(ManagedThreadFactoryRemove.INSTANCE) .addCapabilities(CAPABILITY)); }

Target:
private ManagedThreadFactoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.MANAGED_THREAD_FACTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.MANAGED_THREAD_FACTORY)) .setAddHandler(ManagedThreadFactoryAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(ManagedThreadFactoryAdd.INSTANCE)) .addCapabilities(CAPABILITY)); }
Source:
public IndexedKeyFormatMapper(Collection<? extends KeyFormat<?>> keyFormats) { List<KeyFormat<Object>> list = new ArrayList<>(); for (KeyFormat<?> format : keyFormats) { KeyFormat<Object> objectKeyFormat = (KeyFormat<Object>) format; list.add(objectKeyFormat); } this.keyFormats = list; for (int i = 0; i < this.keyFormats.size(); ++i) { this.indexes.put(this.keyFormats.get(i).getTargetClass(), i); } this.padding = (int) (Math.log(this.keyFormats.size() - 1) / Math.log(HEX_RADIX)) + 1; }

Target:
public IndexedKeyFormatMapper(Collection<? extends KeyFormat<?>> keyFormats) { List<KeyFormat<Object>> list = new ArrayList<>(keyFormats.size()); for (KeyFormat<?> format : keyFormats) { list.add((KeyFormat<Object>) format); } this.keyFormats = list; for (int i = 0; i < this.keyFormats.size(); ++i) { this.indexes.put(this.keyFormats.get(i).getTargetClass(), i); } this.padding = (int) (Math.log(this.keyFormats.size() - 1) / Math.log(HEX_RADIX)) + 1; }
Source:
protected void doStart() { try { configure(); Instant startedAt = Instant.now(); logger().debug("Trying to start container: {}", getDockerImageName()); AtomicInteger attempt = new AtomicInteger(0); Unreliables.retryUntilSuccess(startupAttempts, () -> { logger().debug("Trying to start container: (attempt {}/{})", getDockerImageName(), attempt.incrementAndGet(), startupAttempts); tryStart(startedAt); return true; }); } catch (Exception e) { throw new ContainerLaunchException("Container startup failed", e); } }

Target:
protected void doStart() { try { configure(); Instant startedAt = Instant.now(); logger().debug("Starting container: {}", getDockerImageName()); AtomicInteger attempt = new AtomicInteger(0); Unreliables.retryUntilSuccess(startupAttempts, () -> { logger().debug("Trying to start container: (attempt {}/{})", getDockerImageName(), attempt.incrementAndGet(), startupAttempts); tryStart(startedAt); return true; }); } catch (Exception e) { throw new ContainerLaunchException("Container startup failed", e); } }
Source:
public void testManualIncrementing() throws Exception { expectInitializeNoOffsets(Arrays.asList( SINGLE_TABLE_PARTITION, SINGLE_TABLE_PARTITION_WITH_VERSION)); PowerMock.replayAll(); db.createTable(SINGLE_TABLE_NAME, "id", "INT NOT NULL"); db.insert(SINGLE_TABLE_NAME, "id", 1); startTask(null, "id", null); verifyIncrementingFirstPoll(TOPIC_PREFIX + SINGLE_TABLE_NAME); db.insert(SINGLE_TABLE_NAME, "id", 2); db.insert(SINGLE_TABLE_NAME, "id", 3); verifyPoll(2, "id", Arrays.asList(2, 3), false, true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); PowerMock.verifyAll(); }

Target:
public void testManualIncrementing() throws Exception { expectInitializeNoOffsets(Arrays.asList( SINGLE_TABLE_PARTITION_WITH_VERSION, SINGLE_TABLE_PARTITION) ); PowerMock.replayAll(); db.createTable(SINGLE_TABLE_NAME, "id", "INT NOT NULL"); db.insert(SINGLE_TABLE_NAME, "id", 1); startTask(null, "id", null); verifyIncrementingFirstPoll(TOPIC_PREFIX + SINGLE_TABLE_NAME); db.insert(SINGLE_TABLE_NAME, "id", 2); db.insert(SINGLE_TABLE_NAME, "id", 3); verifyPoll(2, "id", Arrays.asList(2, 3), false, true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); PowerMock.verifyAll(); }
Source:
public OpaqueTokenConfigurer(ApplicationContext context) { this.context = context; }

Target:
OpaqueTokenConfigurer(ApplicationContext context) { this.context = context; }
Source:
public Product(String productId, String name, Owner owner, Long multiplier) { setId(productId); setName(name); setOwners(new HashSet<Owner>()); setMultiplier(multiplier); setAttributes(new HashSet<ProductAttribute>()); setProductContent(new LinkedList<ProductContent>()); setDependentProductIds(new HashSet<String>()); }

Target:
public Product(String productId, String name, Owner owner, Long multiplier) { setId(productId); setName(name); setOwners(new HashSet<Owner>()); setMultiplier(multiplier); setAttributes(new HashSet<ProductAttribute>()); setProductContent(new LinkedList<ProductContent>()); setDependentProductIds(new HashSet<String>()); this.addOwner(owner); }
Source:
public void cannotPlayAGuessTwice() { Observable<Output> result = hangman.play( Observable.fromArray("secret"), Observable.fromArray("e", "c", "s", "c")); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Letter c was already played"); result.blockingLast(); }

Target:
public void cannotPlayAGuessTwice() { Observable<Output> result = hangman.play( Observable.fromArray("secret"), Observable.fromArray("e", "c", "s", "c")); assertThatThrownBy(() -> result.blockingLast()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Letter c was already played"); }
Source:
public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = getStyles(); if (styles == null || styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { @NonNull Map<@NonNull String, @NonNull Object> elementStyle = styleEntry.getValue().getStyleValues(); fLabelToIndex.put(styleEntry.getKey(), tableIndex); tableIndex++; Map<String, Object> styleMap = new HashMap<>(elementStyle); styleMap.put(StyleProperties.STYLE_NAME, styleEntry.getKey()); stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }

Target:
public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = fetchStyles(); if (styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { String styleKey = styleEntry.getKey(); fKeyToIndex.put(styleKey, tableIndex++); OutputElementStyle elementStyle = styleEntry.getValue(); Map<String, Object> styleMap = new HashMap<>(); RGBAColor rgba = getColorStyle(elementStyle, StyleProperties.BACKGROUND_COLOR); RGB rgb = (rgba != null) ? new RGB(rgba.getRed(), rgba.getGreen(), rgba.getBlue()) : new RGB(0, 0, 0); styleMap.put(StyleProperties.BACKGROUND_COLOR, ColorUtils.toHexColor(rgb)); Object styleName = getStyle(elementStyle, StyleProperties.STYLE_NAME); if (styleName instanceof String) { styleMap.put(StyleProperties.STYLE_NAME, styleName); } else { styleMap.put(StyleProperties.STYLE_NAME, styleEntry.getKey()); } Float height = getFloatStyle(elementStyle, StyleProperties.HEIGHT); if (height != null) { styleMap.put(StyleProperties.HEIGHT, height); } Object symbolType = getStyle(elementStyle, StyleProperties.SYMBOL_TYPE); if (symbolType instanceof String) { styleMap.put(StyleProperties.SYMBOL_TYPE, symbolType); } Object styleGroup = getStyle(elementStyle, StyleProperties.STYLE_GROUP); if (styleGroup != null) { styleMap.put(StyleProperties.STYLE_GROUP, styleGroup); } stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }
Source:
public void setVoiceCallForwardingFlag(int line, boolean enable) { if (line != 1) return; callForwardingEnabled = enable; phone.setSystemProperty(PROPERTY_LINE1_VOICE_CALL_FORWARDING, (callForwardingEnabled ? "true" : "false")); ((GSMPhone) phone).notifyCallForwardingIndicator(); try { if (mEfCfis != null) { if (enable) { mEfCfis[1] |= 1; } else { mEfCfis[1] &= 0xfe; } ((SIMFileHandler)phone.getIccFileHandler()).updateEFLinearFixed( EF_CFIS, 1, mEfCfis, null, obtainMessage (EVENT_UPDATE_DONE, EF_CFIS)); } if (mEfCff != null) { if (enable) { mEfCff[0] = (byte) ((mEfCff[0] & CFF_LINE1_RESET) | CFF_UNCONDITIONAL_ACTIVE); } else { mEfCff[0] = (byte) ((mEfCff[0] & CFF_LINE1_RESET) | CFF_UNCONDITIONAL_DEACTIVE); } ((SIMFileHandler)phone.getIccFileHandler()).updateEFTransparent( EF_CFF_CPHS, mEfCff, obtainMessage (EVENT_UPDATE_DONE, EF_CFF_CPHS)); } } catch (ArrayIndexOutOfBoundsException ex) { Log.w(LOG_TAG, "Error saving call fowarding flag to SIM. " + "Probably malformed SIM record", ex); } }

Target:
public void setVoiceCallForwardingFlag(int line, boolean enable) { if (line != 1) return; callForwardingEnabled = enable; phone.setSystemProperty(PROPERTY_LINE1_VOICE_CALL_FORWARDING, (callForwardingEnabled ? "true" : "false")); ((GSMPhone) phone).notifyCallForwardingIndicator(); try { if (mEfCfis != null) { if (enable) { mEfCfis[1] |= 1; } else { mEfCfis[1] &= 0xfe; } phone.getIccFileHandler().updateEFLinearFixed( EF_CFIS, 1, mEfCfis, null, obtainMessage (EVENT_UPDATE_DONE, EF_CFIS)); } if (mEfCff != null) { if (enable) { mEfCff[0] = (byte) ((mEfCff[0] & CFF_LINE1_RESET) | CFF_UNCONDITIONAL_ACTIVE); } else { mEfCff[0] = (byte) ((mEfCff[0] & CFF_LINE1_RESET) | CFF_UNCONDITIONAL_DEACTIVE); } phone.getIccFileHandler().updateEFTransparent( EF_CFF_CPHS, mEfCff, obtainMessage (EVENT_UPDATE_DONE, EF_CFF_CPHS)); } } catch (ArrayIndexOutOfBoundsException ex) { Log.w(LOG_TAG, "Error saving call fowarding flag to SIM. " + "Probably malformed SIM record", ex); } }
Source:
private void registerMacerator(int id) { int subId, completId; String name; { subId = 0; name = TR_NAME(Type.NONE, "50V Macerator"); MaceratorDescriptor desc = new MaceratorDescriptor(name, "maceratora", LVU, 200, LVU * 1.25, new ThermalLoadInitializer(80, -100, 10, 100000.0), lowVoltageCableDescriptor, maceratorRecipes); transparentNodeItem.addDescriptor(subId + (id << 6), desc); desc.setRunningSound("eln:macerator"); } { subId = 4; name = TR_NAME(Type.NONE, "200V Macerator"); MaceratorDescriptor desc = new MaceratorDescriptor(name, "maceratorb", MVU, 1000, MVU * 1.25, new ThermalLoadInitializer(80, -100, 10, 100000.0), meduimVoltageCableDescriptor, maceratorRecipes); transparentNodeItem.addDescriptor(subId + (id << 6), desc); desc.setRunningSound("eln:macerator"); } }

Target:
private void registerMacerator(int id) { int subId, completId; String name; { subId = 0; name = TR_NAME(Type.NONE, "50V Macerator"); MaceratorDescriptor desc = new MaceratorDescriptor(name, "maceratora", LVU, 200, LVU * 1.25, new ThermalLoadInitializer(80, -100, 10, 100000.0), lowVoltageCableDescriptor, maceratorRecipes); transparentNodeItem.addDescriptor(subId + (id << 6), desc); desc.setRunningSound("eln:macerator"); } { subId = 4; name = TR_NAME(Type.NONE, "200V Macerator"); MaceratorDescriptor desc = new MaceratorDescriptor(name, "maceratorb", MVU, 2000, MVU * 1.25, new ThermalLoadInitializer(80, -100, 10, 100000.0), mediumVoltageCableDescriptor, maceratorRecipes); transparentNodeItem.addDescriptor(subId + (id << 6), desc); desc.setRunningSound("eln:macerator"); } }
Source:
public ResultSet executeQuery() throws SQLException { result = null; try { if (eclQuery == null) { String message = "HPCCPreparedStatement: Cannot execute SQL command"; if (warnings != null) { SQLException w = warnings.getNextException(); if(w != null) { message += "\n\t"; message += w.getLocalizedMessage(); } } throw new SQLException(message); } ArrayList dsList = eclQuery.execute(parameters); if (dsList != null) result = new HPCCResultSet(this, dsList, eclQuery.getExpectedRetCols(), "HPCC Result"); } catch (Exception e) { SQLException sqlexcept = new SQLException(e.getLocalizedMessage()); sqlexcept.setStackTrace(e.getStackTrace()); if (warnings == null) warnings = new SQLWarning(); warnings.setNextException(sqlexcept); throw sqlexcept; } return result; }

Target:
public ResultSet executeQuery() throws SQLException { result = null; try { if (!this.closed) { if (eclQuery == null) { String message = "HPCCPreparedStatement: Cannot execute SQL command"; if (warnings != null) { SQLException w = warnings.getNextException(); if(w != null) { message += "\n\t"; message += w.getLocalizedMessage(); } } throw new SQLException(message); } ArrayList dsList = eclQuery.execute(parameters); if (dsList != null) result = new HPCCResultSet(this, dsList, eclQuery.getExpectedRetCols(), "HPCC Result"); } else throw new SQLException("HPCCPreparedStatement closed, cannot execute query"); } catch (Exception e) { SQLException sqlexcept = new SQLException(e.getLocalizedMessage()); sqlexcept.setStackTrace(e.getStackTrace()); if (warnings == null) warnings = new SQLWarning(); warnings.setNextException(sqlexcept); throw sqlexcept; } return result; }
Source:
private static byte[] generateHmacSha256Bytes(String key, String valueToEncrypt) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKey); mac.update(valueToEncrypt.getBytes("UTF-8")); byte[] hmacData = mac.doFinal(); return hmacData; } catch (UnsupportedEncodingException | IllegalStateException | InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
private static byte[] generateHmacSha256Bytes(String key, String valueToEncrypt) throws UnsupportedEncodingException, IllegalStateException, InvalidKeyException, NoSuchAlgorithmException { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKey); mac.update(valueToEncrypt.getBytes("UTF-8")); byte[] hmacData = mac.doFinal(); return hmacData; }
Source:
public void setServerNames(String[] serverNames) { if (serverNames == null || serverNames.length == 0 || serverNames[0].equals("")) { this.serverNames = new String[] {"localhost"}; } else { this.serverNames = serverNames; } }

Target:
public void setServerNames(String[] serverNames) { if (serverNames == null || serverNames.length == 0) { this.serverNames = new String[] {"localhost"}; } else { serverNames = Arrays.copyOf(serverNames, serverNames.length); for (int i = 0; i < serverNames.length; i++) { if (serverNames[i] == null || serverNames[i].equals("")) { serverNames[i] = "localhost"; } } this.serverNames = serverNames; } }
Source:
public void afterPropertiesSet() throws Exception { this.sslContext = this.sslContextSupport.getSSLContext(); Assert.notNull(this.sslContext, "SSLContext must not be null"); }

Target:
public void afterPropertiesSet() throws Exception { }
Source:
protected View onCreateDialogView() { ScrollView outterView = new ScrollView(getContext()); outterView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); LinearLayout innerView = new LinearLayout(getContext()); innerView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); innerView.setOrientation(LinearLayout.VERTICAL); View spacerView = new View(getContext()); int spacerHeight = getContext().getResources().getDimensionPixelSize(R.dimen.margin_medium); spacerView.setLayoutParams(new ViewGroup.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, spacerHeight)); innerView.addView(spacerView); outterView.addView(innerView); configureLayoutForView(innerView); return outterView; }

Target:
protected View onCreateDialogView() { ScrollView outerView = new ScrollView(getContext()); outerView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); LinearLayout innerView = new LinearLayout(getContext()); innerView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); innerView.setOrientation(LinearLayout.VERTICAL); View spacerView = new View(getContext()); int spacerHeight = getContext().getResources().getDimensionPixelSize(R.dimen.margin_medium); spacerView.setLayoutParams(new ViewGroup.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, spacerHeight)); innerView.addView(spacerView); outerView.addView(innerView); configureLayoutForView(innerView); return outerView; }
Source:
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { if (!sealed) { int size = (int)ExtUtil.readNumeric(in); try { List<Object> l = listImplementation.newInstance(); for (int i = 0; i < size; i++) { l.add(ExtUtil.read(in, type, pf)); } val = l; } catch (InstantiationException e) { throw new DeserializationException(e.getMessage()); } catch (IllegalAccessException e) { throw new DeserializationException(e.getMessage()); } } else { int size = (int)ExtUtil.readNumeric(in); Object[] theval = new Object[size]; for (int i = 0; i < size; i++) { theval[i] = ExtUtil.read(in, type, pf); } val = theval; } }

Target:
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { if (!sealed) { int size = (int)ExtUtil.readNumeric(in); try { List<Object> l; if (listImplementation.equals(Vector.class)) { l = new Vector<>(size); } else { l = listImplementation.newInstance(); } for (int i = 0; i < size; i++) { l.add(ExtUtil.read(in, type, pf)); } val = l; } catch (InstantiationException e) { throw new DeserializationException(e.getMessage()); } catch (IllegalAccessException e) { throw new DeserializationException(e.getMessage()); } } else { int size = (int)ExtUtil.readNumeric(in); Object[] theval = new Object[size]; for (int i = 0; i < size; i++) { theval[i] = ExtUtil.read(in, type, pf); } val = theval; } }
Source:
public List<LifeCycle> getLifecycle() { if (null == lifecycle) { this.lifecycle = new ArrayList<>(); } return lifecycle; }

Target:
public List<LifeCycle> getLifecycle() { return lifecycle; }
Source:
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData, Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask("Submitting_task", IProgressMonitor.UNKNOWN); BugzillaRestClient client = connector.getClient(repository); try { IOperationMonitor progress = OperationUtil.convert(monitor, "post taskdata", 3); progress.addFlag(OperationFlag.BACKGROUND); return client.postTaskData(taskData, progress); } catch (BugzillaRestException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 2, "Error post taskdata.\n\n" + e.getMessage(), e)); } } finally { monitor.done(); } }

Target:
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData, Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask("Submitting_task", IProgressMonitor.UNKNOWN); BugzillaRestClient client = connector.getClient(repository); try { IOperationMonitor progress = OperationUtil.convert(monitor, "post taskdata", 3); return client.postTaskData(taskData, progress); } catch (BugzillaRestException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 2, "Error post taskdata.\n\n" + e.getMessage(), e)); } } finally { monitor.done(); } }
Source:
public void close() { if (this.closed) { return; } assign(ImmutableSet.of()); scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.info(e, "InterruptedException while shutting down"); } this.closed = true; }

Target:
public void close() { if (this.closed) { return; } assign(ImmutableSet.of()); scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); throw new RuntimeException(e); } this.closed = true; }
Source:
public void setsVisibility() throws Exception { final File dir = Files.createTempDir(); final Base base = new MkBase(dir); final String name = "setsVisibility.txt"; final Docs docs = base.user("urn:test:1").docs(); final Doc doc = docs.doc(name); final File file = dir.toPath().resolve(Paths.get("urn/test/1", name)) .toFile(); file.getParentFile().mkdirs(); file.createNewFile(); MatcherAssert.assertThat( doc.attributes().visible(), Matchers.is(false) ); MatcherAssert.assertThat( new RsPrint( new TkSetVisibility(base).act( new RqWithTester( new RqFake( TkSetVisibilityTest.POST, new Href() .with(TkSetVisibilityTest.FILE, name) .with(TkSetVisibilityTest.VISIBILITY, "Public") ) ) ) ).print(), Matchers.containsString("document+visibility+set+to") ); MatcherAssert.assertThat( doc.attributes().visible(), Matchers.is(true) ); }

Target:
public void setsVisibility() throws Exception { final Base base = new MkBase(); final String name = "setsVisibility.txt"; final Doc doc = base.user("urn:test:1").docs().doc(name); doc.write(new ByteArrayInputStream(new byte[1]), 1); MatcherAssert.assertThat( doc.attributes().visible(), Matchers.is(false) ); MatcherAssert.assertThat( new RsPrint( new TkSetVisibility(base).act( new RqWithTester( new RqFake( TkSetVisibilityTest.POST, new Href() .with(TkSetVisibilityTest.FILE, name) .with(TkSetVisibilityTest.VISIBILITY, "Public") ) ) ) ).print(), Matchers.containsString("document+visibility+set+to") ); MatcherAssert.assertThat( doc.attributes().visible(), Matchers.is(true) ); }
Source:
private static boolean proposePaxos(Commit proposal, ReplicaList replicas, int requiredParticipants, boolean timeoutIfPartial, ConsistencyLevel consistencyLevel, long queryStartNanoTime) throws WriteTimeoutException { ProposeCallback callback = new ProposeCallback(replicas.size(), requiredParticipants, !timeoutIfPartial, consistencyLevel, queryStartNanoTime); MessageOut<Commit> message = new MessageOut<Commit>(MessagingService.Verb.PAXOS_PROPOSE, proposal, Commit.serializer); for (InetAddressAndPort target : replicas.asEndpoints()) { if (canDoLocalRequest(target)) { StageManager.getStage(MessagingService.verbStages.get(MessagingService.Verb.PAXOS_PROPOSE)).execute(new Runnable() { public void run() { try { MessageIn<Boolean> message = MessageIn.create(FBUtilities.getBroadcastAddressAndPort(), ProposeVerbHandler.doPropose(proposal), Collections.emptyMap(), MessagingService.Verb.INTERNAL_RESPONSE, MessagingService.current_version); callback.response(message); } catch (Exception ex) { logger.error("Failed paxos propose locally", ex); } } }); } else { MessagingService.instance().sendRR(message, target, callback); } } callback.await(); if (callback.isSuccessful()) return true; if (timeoutIfPartial && !callback.isFullyRefused()) throw new WriteTimeoutException(WriteType.CAS, consistencyLevel, callback.getAcceptCount(), requiredParticipants); return false; }

Target:
private static boolean proposePaxos(Commit proposal, ReplicaList replicas, int requiredParticipants, boolean timeoutIfPartial, ConsistencyLevel consistencyLevel, long queryStartNanoTime) throws WriteTimeoutException { ProposeCallback callback = new ProposeCallback(replicas.size(), requiredParticipants, !timeoutIfPartial, consistencyLevel, queryStartNanoTime); MessageOut<Commit> message = new MessageOut<Commit>(MessagingService.Verb.PAXOS_PROPOSE, proposal, Commit.serializer); for (Replica replica : replicas) { if (canDoLocalRequest(replica.getEndpoint())) { StageManager.getStage(MessagingService.verbStages.get(MessagingService.Verb.PAXOS_PROPOSE)).execute(new Runnable() { public void run() { try { MessageIn<Boolean> message = MessageIn.create(FBUtilities.getBroadcastAddressAndPort(), ProposeVerbHandler.doPropose(proposal), Collections.emptyMap(), MessagingService.Verb.INTERNAL_RESPONSE, MessagingService.current_version); callback.response(message); } catch (Exception ex) { logger.error("Failed paxos propose locally", ex); } } }); } else { MessagingService.instance().sendRR(message, replica.getEndpoint(), callback); } } callback.await(); if (callback.isSuccessful()) return true; if (timeoutIfPartial && !callback.isFullyRefused()) throw new WriteTimeoutException(WriteType.CAS, consistencyLevel, callback.getAcceptCount(), requiredParticipants); return false; }
Source:
protected BuyClient getBuyClient(String shopDomain, String apiKey, String appId, String applicationName) { final BuyClientBuilder buyClientBuilder = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .callbackScheduler(Schedulers.immediate()) .productPageSize(PRODUCT_PAGE_SIZE) .collectionPageSize(COLLECTION_PAGE_SIZE) .productTagPageSize(PRODUCT_TAG_PAGE_SIZE) .httpTimeout(TimeUnit.SECONDS.toMillis(60), TimeUnit.SECONDS.toMillis(60)) .networkRequestRetryPolicy(1, 100, 1); if (USE_MOCK_RESPONSES) { buyClientBuilder.httpInterceptors(new MockResponder(context), new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } else if (GENERATE_MOCK_RESPONSES) { buyClientBuilder.httpInterceptors(new MockResponseGenerator(context), new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } else { buyClientBuilder.httpInterceptors(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } buyClient = buyClientBuilder.build(); return buyClient; }

Target:
protected BuyClient getBuyClient(String shopDomain, String apiKey, String appId, String applicationName) { final BuyClientBuilder buyClientBuilder = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .callbackScheduler(Schedulers.immediate()) .productRequestPageSize(PRODUCT_PAGE_SIZE) .collectionRequestPageSize(COLLECTION_PAGE_SIZE) .productTagRequesPageSize(PRODUCT_TAG_PAGE_SIZE) .httpTimeout(TimeUnit.SECONDS.toMillis(60), TimeUnit.SECONDS.toMillis(60)) .networkRequestRetryPolicy(1, 100, 1); if (USE_MOCK_RESPONSES) { buyClientBuilder.httpInterceptors(new MockResponder(context), new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } else if (GENERATE_MOCK_RESPONSES) { buyClientBuilder.httpInterceptors(new MockResponseGenerator(context), new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } else { buyClientBuilder.httpInterceptors(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); } buyClient = buyClientBuilder.build(); return buyClient; }
Source:
private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); } catch (Throwable th) { logger.error("Error in unmarshalling the object:", th); } }

Target:
private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); } catch (Exception ex) { logger.error("Error in unmarshalling the object:", ex); } }
Source:
private void updateStream() throws IOException { if (mBlockInStream != null && mBlockInStream.remaining() > 0) { return; } if (mBlockInStream != null && mBlockInStream.remaining() == 0) { closeBlockInStream(mBlockInStream); } long blockId = mStatus.getBlockIds().get(Math.toIntExact(mPosition / mBlockSize)); BlockInfo blockInfo = mStatus.getBlockInfo(blockId); if (blockInfo == null) { throw new IOException("Block " + blockId + " does not exist"); } mBlockInStream = mBlockStore.getInStream(blockInfo, mOptions, mFailedWorkers); long offset = mPosition % mBlockSize; mBlockInStream.seek(offset); }

Target:
private void updateStream() throws IOException { if (mBlockInStream != null && mBlockInStream.remaining() > 0) { return; } if (mBlockInStream != null && mBlockInStream.remaining() == 0) { closeBlockInStream(mBlockInStream); } long blockId = mStatus.getBlockIds().get(Math.toIntExact(mPosition / mBlockSize)); BlockInfo blockInfo = mStatus.getBlockInfo(blockId); if (blockInfo == null) { throw new IOException("No BlockInfo for block(id=" + blockId + ") of file" + "(id=" + mStatus.getFileId() + ", path=" + mStatus.getPath() + ")"); } boolean isBlockInfoOutdated = true; for (BlockLocation location : blockInfo.getLocations()) { if (!mFailedWorkers.containsKey(location.getWorkerAddress())) { isBlockInfoOutdated = false; break; } } if (isBlockInfoOutdated) { mBlockInStream = mBlockStore.getInStream(blockId, mOptions, mFailedWorkers); } else { mBlockInStream = mBlockStore.getInStream(blockInfo, mOptions, mFailedWorkers); } long offset = mPosition % mBlockSize; mBlockInStream.seek(offset); }
Source:
public void bindServiceShouldCallOnServiceConnectedWithDefaultValues() { TestService service = new TestService(); ComponentName expectedComponentName = new ComponentName("", ""); NullBinder expectedBinder = new NullBinder(); Shadows.shadowOf(RuntimeEnvironment.application).setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); RuntimeEnvironment.application.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE); assertEquals(expectedComponentName, service.name); assertEquals(expectedBinder, service.service); assertNull(service.nameUnbound); RuntimeEnvironment.application.unbindService(service); assertEquals(expectedComponentName, service.nameUnbound); }

Target:
public void bindServiceShouldCallOnServiceConnectedWithDefaultValues() { TestService service = new TestService(); ComponentName expectedComponentName = new ComponentName("", ""); NullBinder expectedBinder = new NullBinder(); Shadows.shadowOf(RuntimeEnvironment.application).setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); RuntimeEnvironment.application.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE); assertThat(service.name).isEqualTo(expectedComponentName); assertThat(service.service).isEqualTo(expectedBinder); assertThat(service.nameUnbound).isNull(); RuntimeEnvironment.application.unbindService(service); assertThat(service.nameUnbound).isEqualTo(expectedComponentName); }