auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isHttpWebsite(String siteUrl) throws IOException { URL url = new URL("http://" + siteUrl); HttpURLConnection httpCon = (HttpURLConnection)url.openConnection(); int responseCode = 0; if (httpCon == null) return (false); try { responseCode = httpCon.getResponseCode(); } catch (UnknownHostException e) { e.printStackTrace(); return (false); } httpCon.disconnect(); if (responseCode == 200) return (true); return (false); }

Target:
private boolean isHttpWebsite(String siteUrl) throws IOException { URL url = new URL("http://" + siteUrl); HttpURLConnection httpCon = (HttpURLConnection)url.openConnection(); int responseCode = 0; if (httpCon == null) return (false); try { responseCode = httpCon.getResponseCode(); } catch (UnknownHostException e) { Log.e("URLHelper", "UnknownHostException", e.getCause()); return (false); } httpCon.disconnect(); if (responseCode == 200) return (true); return (false); }
Source:
static <K, V, M extends Map<K, V>> M replaceValue(M map, K key, V value) { return map.containsKey(key) ? put(map, Tuple(key, value)) : map; }

Target:
static <K, V, M extends Map<K, V>> M replaceValue(M map, K key, V value) { return map.containsKey(key) ? (M) map.put(key, value) : map; }
Source:
protected void recomputeNumBuckets() { if(useSystemTime){ Calendar calendar = Calendar.getInstance(); long now = calendar.getTimeInMillis()/1000; calendar.add(Calendar.SECOND, (int) -expiryPeriod); startOfBuckets = calendar.getTimeInMillis()/1000; expiryPoint = startOfBuckets; noOfBuckets = (int) Math.ceil((now - startOfBuckets) / (bucketSpan * 1.0)) + 1; logger.debug("Now {}, StartOfBuckets {}, Expiry Point {}, Num Buckets {}, Expiry Period: {}", now, startOfBuckets, expiryPoint, noOfBuckets, expiryPeriod); } else{ startOfBuckets = 0; expiryPoint = startOfBuckets; noOfBuckets = (int) Math.ceil((expiryPeriod) / (bucketSpan * 1.0)) + 1; } noOfBucketsInMemory = noOfBuckets; if (bucketStore != null) { bucketStore.setNoOfBuckets(noOfBuckets); bucketStore.setWriteEventKeysOnly(writeEventKeysOnly); } maxExpiryPerBucket = new Long[noOfBuckets]; }

Target:
protected void recomputeNumBuckets() { if(useSystemTime){ Calendar calendar = Calendar.getInstance(); long now = calendar.getTimeInMillis() / 1000; calendar.add(Calendar.SECOND, (int) -expiryPeriod); startOfBuckets = calendar.getTimeInMillis() / 1000; expiryPoint = startOfBuckets; noOfBuckets = (int) Math.ceil(( now - startOfBuckets ) / ( bucketSpan * 1.0 )) + 1; logger.debug("Now {}, StartOfBuckets {}, Expiry Point {}, Num Buckets {}, Expiry Period: {}", now, startOfBuckets, expiryPoint, noOfBuckets, expiryPeriod); } else{ startOfBuckets = 0; expiryPoint = startOfBuckets; noOfBuckets = (int) Math.ceil((expiryPeriod) / (bucketSpan * 1.0)) + 1; } noOfBucketsInMemory = noOfBuckets; if (bucketStore != null) { bucketStore.setNoOfBuckets(noOfBuckets); bucketStore.setWriteEventKeysOnly(writeEventKeysOnly); } maxExpiryPerBucket = new long[noOfBuckets]; }
Source:
void setUp() { aggregateIdentifier = UUID.randomUUID().toString(); commandBus = SimpleCommandBus.builder().build(); eventStore = spy(EmbeddedEventStore.builder().storageEngine(new InMemoryEventStorageEngine()).build()); eventStore.publish(new GenericDomainEventMessage<>(CountingAggregate.class.getSimpleName(), aggregateIdentifier, 0, new AggregateCreatedEvent(aggregateIdentifier), null)); reset(eventStore); reportErrorCallback = (commandMessage, commandResultMessage) -> { if (commandResultMessage.isExceptional()) { Throwable cause = commandResultMessage.exceptionResult(); throw new RuntimeException("Failure", cause); } }; expectErrorCallback = (commandMessage, commandResultMessage) -> { if (commandResultMessage.isExceptional()) { Throwable cause = commandResultMessage.exceptionResult(); assertEquals("Mock exception", cause.getMessage()); } else { fail("Expected this command to fail"); } }; }

Target:
void setUp() { aggregateIdentifier = UUID.randomUUID().toString(); commandBus = SimpleCommandBus.builder().build(); eventStore = spy(EmbeddedEventStore.builder().storageEngine(new InMemoryEventStorageEngine()).build()); eventStore.publish(new GenericDomainEventMessage<>("test", aggregateIdentifier, 0, new AggregateCreatedEvent(aggregateIdentifier), null)); reset(eventStore); reportErrorCallback = (commandMessage, commandResultMessage) -> { if (commandResultMessage.isExceptional()) { Throwable cause = commandResultMessage.exceptionResult(); throw new RuntimeException("Failure", cause); } }; expectErrorCallback = (commandMessage, commandResultMessage) -> { if (commandResultMessage.isExceptional()) { Throwable cause = commandResultMessage.exceptionResult(); assertEquals("Mock exception", cause.getMessage()); } else { fail("Expected this command to fail"); } }; }
Source:
protected void executeVmCommand() { importVmLease(); super.executeVmCommand(); }

Target:
protected void executeVmCommand() { handleVmLease(); super.executeVmCommand(); }
Source:
public void closeSearch() { isSearchActive = false; getActivity().supportInvalidateOptionsMenu(); getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }

Target:
public void closeSearch() { isSearchActive = false; getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }
Source:
public static boolean hasCompatibleCapabilities( RecordFormats one, RecordFormats other, CapabilityType type ) { Set<Capability> myFormatCapabilities = Stream.of( one.capabilities() ) .filter( capability -> capability.isType( type ) ).collect( toSet() ); Set<Capability> otherFormatCapabilities = Stream.of( other.capabilities() ) .filter( capability -> capability.isType( type ) ).collect( toSet() ); if ( myFormatCapabilities.equals( otherFormatCapabilities ) ) { return true; } Set<Capability> removedCapabilities = new HashSet<>( myFormatCapabilities ).stream().filter( capability -> !otherFormatCapabilities.contains( capability ) ).collect( toSet() ); Set<Capability> addedCapabilities = new HashSet<>( otherFormatCapabilities ).stream().filter( capability -> !myFormatCapabilities.contains( capability ) ).collect( toSet() ); boolean allAddedAreAdditive = addedCapabilities.stream().allMatch( Capability::isAdditive ); if ( removedCapabilities.isEmpty() && allAddedAreAdditive ) { return true; } return false; }

Target:
public static boolean hasCompatibleCapabilities( RecordFormats one, RecordFormats other, CapabilityType type ) { Set<Capability> myFormatCapabilities = Stream.of( one.capabilities() ) .filter( capability -> capability.isType( type ) ).collect( toSet() ); Set<Capability> otherFormatCapabilities = Stream.of( other.capabilities() ) .filter( capability -> capability.isType( type ) ).collect( toSet() ); if ( myFormatCapabilities.equals( otherFormatCapabilities ) ) { return true; } boolean capabilitiesNotRemoved = otherFormatCapabilities.containsAll( myFormatCapabilities ); otherFormatCapabilities.removeAll( myFormatCapabilities ); boolean allAddedAreAdditive = otherFormatCapabilities.stream().allMatch( Capability::isAdditive ); return capabilitiesNotRemoved && allAddedAreAdditive; }
Source:
public List<Metric> getMetrics() throws AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException { Map<String, List<Metric>> subMetrics = new HashMap<String, List<Metric>>(); for (Map.Entry<String, List<String>> entry : subAttributeList.entrySet()) { String dataKey = entry.getKey(); List<String> subSub = entry.getValue(); for (String metricKey : subSub) { String alias = getAlias(metricKey); String metricType = getMetricType(metricKey); String[] tags = getTags(dataKey, metricKey); Metric metric = new Metric(alias, metricType, tags, checkName); double value = castToDouble(getValue(dataKey, metricKey), null); metric.setValue(value); String fullMetricKey = getAttributeName() + "." + metricKey; if (!subMetrics.containsKey(fullMetricKey)) { subMetrics.put(fullMetricKey, new ArrayList<Metric>()); } subMetrics.get(fullMetricKey).add(new Metric(alias, metricType, value, tags)); } } List<Metric> metrics = new ArrayList<Metric>(subMetrics.keySet().size()); for (String key : subMetrics.keySet()) { if (getAttributesFor(key) != null) { metrics.addAll(sortAndFilter(key, subMetrics.get(key))); } } return metrics; }

Target:
public List<Metric> getMetrics() throws AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException { Map<String, List<Metric>> subMetrics = new HashMap<String, List<Metric>>(); for (Map.Entry<String, List<String>> entry : subAttributeList.entrySet()) { String dataKey = entry.getKey(); List<String> subSub = entry.getValue(); for (String metricKey : subSub) { String alias = getAlias(metricKey); String metricType = getMetricType(metricKey); String[] tags = getTags(dataKey, metricKey); Metric metric = new Metric(alias, metricType, tags, checkName); double value = castToDouble(getValue(dataKey, metricKey), null); metric.setValue(value); String fullMetricKey = getAttributeName() + "." + metricKey; if (!subMetrics.containsKey(fullMetricKey)) { subMetrics.put(fullMetricKey, new ArrayList<Metric>()); } subMetrics.get(fullMetricKey).add(metric); } } List<Metric> metrics = new ArrayList<Metric>(subMetrics.keySet().size()); for (String key : subMetrics.keySet()) { if (getAttributesFor(key) != null) { metrics.addAll(sortAndFilter(key, subMetrics.get(key))); } } return metrics; }
Source:
private void registerBrush(int id) { int subId, completId; BrushDescriptor whiteDesc = null; String name; String[] subNames = { TR_NAME(Type.NONE, "Black Brush"), TR_NAME(Type.NONE, "Red Brush"), TR_NAME(Type.NONE, "Green Brush"), TR_NAME(Type.NONE, "Brown Brush"), TR_NAME(Type.NONE, "Blue Brush"), TR_NAME(Type.NONE, "Purple Brush"), TR_NAME(Type.NONE, "Cyan Brush"), TR_NAME(Type.NONE, "Silver Brush"), TR_NAME(Type.NONE, "Gray Brush"), TR_NAME(Type.NONE, "Pink Brush"), TR_NAME(Type.NONE, "Lime Brush"), TR_NAME(Type.NONE, "Yellow Brush"), TR_NAME(Type.NONE, "Light Blue Brush"), TR_NAME(Type.NONE, "Magenta Brush"), TR_NAME(Type.NONE, "Orange Brush"), TR_NAME(Type.NONE, "White Brush")}; for (int idx = 0; idx < 16; idx++) { subId = idx; name = subNames[idx]; BrushDescriptor desc = new BrushDescriptor(name); sharedItem.addElement(subId + (id << 6), desc); whiteDesc = desc; } ItemStack emptyStack = findItemStack("White Brush"); whiteDesc.setLife(emptyStack, 0); for (int idx = 0; idx < 16; idx++) { addShapelessRecipe(emptyStack.copy(), new ItemStack(Blocks.wool, 1, idx), findItemStack("Iron Cable")); } for (int idx = 0; idx < 16; idx++) { name = subNames[idx]; addShapelessRecipe(findItemStack(name, 1), new ItemStack(Items.dye, 1, idx), emptyStack.copy()); } }

Target:
private void registerBrush(int id) { int subId, completId; BrushDescriptor whiteDesc = null; String name; String[] subNames = { TR_NAME(Type.NONE, "Black Brush"), TR_NAME(Type.NONE, "Red Brush"), TR_NAME(Type.NONE, "Green Brush"), TR_NAME(Type.NONE, "Brown Brush"), TR_NAME(Type.NONE, "Blue Brush"), TR_NAME(Type.NONE, "Purple Brush"), TR_NAME(Type.NONE, "Cyan Brush"), TR_NAME(Type.NONE, "Silver Brush"), TR_NAME(Type.NONE, "Gray Brush"), TR_NAME(Type.NONE, "Pink Brush"), TR_NAME(Type.NONE, "Lime Brush"), TR_NAME(Type.NONE, "Yellow Brush"), TR_NAME(Type.NONE, "Light Blue Brush"), TR_NAME(Type.NONE, "Magenta Brush"), TR_NAME(Type.NONE, "Orange Brush"), TR_NAME(Type.NONE, "White Brush")}; for (int idx = 0; idx < 16; idx++) { subId = idx; name = subNames[idx]; BrushDescriptor desc = new BrushDescriptor(name); sharedItem.addElement(subId + (id << 6), desc); whiteDesc = desc; } ItemStack emptyStack = findItemStack("White Brush"); whiteDesc.setLife(emptyStack, 0); for (int idx = 0; idx < 16; idx++) { addShapelessRecipe(emptyStack.copy(), new ItemStack(Blocks.wool, 1, idx), new ItemStack(Items.iron_ingot)); } for (int idx = 0; idx < 16; idx++) { name = subNames[idx]; addShapelessRecipe(findItemStack(name, 1), new ItemStack(Items.dye, 1, idx), emptyStack.copy()); } }
Source:
public RqWithDefaultHeader(final Request req, final String hdr, final String val) { try { if (new RqHeaders.Base(req) .header(hdr) .iterator() .hasNext() ) { this.request = req; } else { this.request = new RqWithHeader(req, hdr, val); } } catch (final IOException ex) { throw new IllegalStateException(ex); } }

Target:
public RqWithDefaultHeader(final Request req, final String hdr, final String val) throws IOException { super(RqWithDefaultHeader.buildRequest(req, hdr, val)); }
Source:
public Set<IProject> getProjects(Set<IReferencePoint> referencePoints) { if (referencePoints == null) throw new IllegalArgumentException("Set of reference points is null"); Set<IProject> projectSet = new HashSet<IProject>(); for (IReferencePoint referencePoint : referencePoints) { if (referencePointToProjectMapper.containsKey(referencePoint)) projectSet.add(get(referencePoint)); } return projectSet; }

Target:
public Set<IProject> getProjects(Set<IReferencePoint> referencePoints) { if (referencePoints == null) throw new IllegalArgumentException("Set of reference points is null"); Set<IProject> projectSet = new HashSet<>(); for (IReferencePoint referencePoint : referencePoints) { if (referencePointToProjectMapper.containsKey(referencePoint)) projectSet.add(getProject(referencePoint)); } return projectSet; }
Source:
public void testEndTime() { Trace trace = new Trace(); trace.setStartTime(100); Consumer node1 = new Consumer(); node1.setBaseTime(100000000); trace.getNodes().add(node1); Component node2 = new Component(); node2.setBaseTime(150000000); node2.setDuration(0); node1.getNodes().add(node2); Producer node3 = new Producer(); node3.setBaseTime(200000000); node3.setDuration(50000000); node1.getNodes().add(node3); assertEquals(150000100, trace.endTime()); }

Target:
public void testEndTime() { Trace trace = new Trace(); trace.setStartTime(100000); Consumer node1 = new Consumer(); node1.setBaseTime(100000); trace.getNodes().add(node1); Component node2 = new Component(); node2.setBaseTime(150000); node2.setDuration(0); node1.getNodes().add(node2); Producer node3 = new Producer(); node3.setBaseTime(200000); node3.setDuration(50000); node1.getNodes().add(node3); assertEquals(250000, trace.endTime()); }
Source:
private static void logException(Throwable e) { Platform.getLog(AntCorePlugin.getPlugin().getBundle()).log(new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, "", e)); }

Target:
private static void logException(Throwable e) { Platform.getLog(AntCorePlugin.getPlugin().getBundle()).log(new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, e.getLocalizedMessage(), e)); }
Source:
public static Document makeEnhancementOperationBody(String userid, PID pid, Boolean force) { Document msg = new Document(); Element entry = new Element("entry", ATOM_NS); entry.addContent(new Element("author", ATOM_NS) .addContent(new Element("name", ATOM_NS).setText(userid))); Element paramForce = new Element("force", CDR_MESSAGE_NS); if (force) { paramForce.setText("true"); } else { paramForce.setText("false"); } Element enhancements = new Element(ENHANCEMENTS.getName(), ATOM_NS); enhancements.addContent(new Element("pid", ATOM_NS).setText(pid.getRepositoryPath())); enhancements.addContent(paramForce); entry.addContent(enhancements); msg.addContent(entry); return msg; }

Target:
public static Document makeEnhancementOperationBody(String userid, PID pid, Boolean force) { Document msg = new Document(); Element entry = new Element("entry", ATOM_NS); entry.addContent(new Element("author", ATOM_NS) .addContent(new Element("name", ATOM_NS).setText(userid))); Element paramForce = new Element("force", CDR_MESSAGE_NS); if (force) { paramForce.setText("true"); } else { paramForce.setText("false"); } Element enhancements = new Element(RUN_ENHANCEMENTS.getName(), CDR_MESSAGE_NS); enhancements.addContent(new Element("pid", CDR_MESSAGE_NS).setText(pid.getRepositoryPath())); enhancements.addContent(paramForce); entry.addContent(enhancements); msg.addContent(entry); return msg; }
Source:
public int queryReplicationStatus() { if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE) { if (replicationManager != null) { return replicationManager.queryReplicationStatus(); } return 0; } else { log.warn("Illegal queryReplicationStatus when cluster{} with role {}", localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); return -1; } }

Target:
public int queryReplicationStatus() { if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE) { if (!isLeader) { log.warn("Illegal queryReplicationStatus when node is not a leader " + "in an ACTIVE Cluster{} ", localClusterDescriptor.getClusterId()); return 0; } if (replicationManager == null) { log.warn("Illegal queryReplicationStatus when replication manager is null " + "in an ACTIVE Cluster{} ", localClusterDescriptor.getClusterId()); return 0; } return replicationManager.queryReplicationStatus(); } else { log.warn("Illegal queryReplicationStatus when cluster{} with role {}", localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); return INVALID_REPLICATION_STATUS; } }
Source:
public byte[] decrypt(InputStream from, byte[] AAD) { byte[] lengthBuffer = new byte[SIZE_LENGTH]; int gotBytes = 0; while (gotBytes < SIZE_LENGTH) { int n; try { n = from.read(lengthBuffer, gotBytes, SIZE_LENGTH - gotBytes); } catch (IOException e) { throw new ParquetCryptoRuntimeException(e); } if (n <= 0) { throw new ParquetCryptoRuntimeException("Tried to read int (4 bytes), but only got " + gotBytes + " bytes."); } gotBytes += n; } final int ciphertextLength = ((lengthBuffer[3] & 0xff) << 24) | ((lengthBuffer[2] & 0xff) << 16) | ((lengthBuffer[1] & 0xff) << 8) | ((lengthBuffer[0] & 0xff)); if (ciphertextLength < 1) { throw new ParquetCryptoRuntimeException("Wrong length of encrypted metadata: " + ciphertextLength); } byte[] ciphertextBuffer = new byte[ciphertextLength]; gotBytes = 0; while (gotBytes < ciphertextLength) { int n; try { n = from.read(ciphertextBuffer, gotBytes, ciphertextLength - gotBytes); } catch (IOException e) { throw new ParquetCryptoRuntimeException(e); } if (n <= 0) { throw new ParquetCryptoRuntimeException("Tried to read " + ciphertextLength + " bytes, but only got " + gotBytes + " bytes."); } gotBytes += n; } return decrypt(ciphertextBuffer, 0, ciphertextLength, AAD); }

Target:
public byte[] decrypt(InputStream from, byte[] AAD) throws IOException { byte[] lengthBuffer = new byte[SIZE_LENGTH]; int gotBytes = 0; while (gotBytes < SIZE_LENGTH) { int n = from.read(lengthBuffer, gotBytes, SIZE_LENGTH - gotBytes); if (n <= 0) { throw new IOException("Tried to read int (4 bytes), but only got " + gotBytes + " bytes."); } gotBytes += n; } final int ciphertextLength = ((lengthBuffer[3] & 0xff) << 24) | ((lengthBuffer[2] & 0xff) << 16) | ((lengthBuffer[1] & 0xff) << 8) | ((lengthBuffer[0] & 0xff)); if (ciphertextLength < 1) { throw new IOException("Wrong length of encrypted metadata: " + ciphertextLength); } byte[] ciphertextBuffer = new byte[ciphertextLength]; gotBytes = 0; while (gotBytes < ciphertextLength) { int n = from.read(ciphertextBuffer, gotBytes, ciphertextLength - gotBytes); if (n <= 0) { throw new IOException("Tried to read " + ciphertextLength + " bytes, but only got " + gotBytes + " bytes."); } gotBytes += n; } return decrypt(ciphertextBuffer, 0, ciphertextLength, AAD); }
Source:
private Map<String, VariantAnnotation> getStoredVariantAnnotations(Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = new HashMap<>(); BasicDBObject query = generateQueryForAnnotationInVariant(variantAnnotations.keySet().toArray(new String[]{})); Iterator<DBObject> iterator = mongoOperations.getCollection(collection).find(query).iterator(); while (iterator.hasNext()) { final DBObject object = iterator.next(); final String id = (String) object.get(ID); final BasicDBList dbAnnotations = (BasicDBList) object.get(ANNOTATION_FIELD); if (dbAnnotations != null && !dbAnnotations.isEmpty()) { final DBObject dbAnnotation = (DBObject) dbAnnotations.get(0); storedVariantAnnotations.put(id, convertToVariantAnnotation(dbAnnotation)); } } return storedVariantAnnotations; }

Target:
private Map<String, VariantAnnotation> getStoredVariantAnnotations(Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = new HashMap<>(); BasicDBObject query = generateQueryForAnnotationInVariant(variantAnnotations.keySet().toArray(new String[]{})); BasicDBObject projection = new BasicDBObject(ANNOTATION_FIELD, 1); Iterator<DBObject> iterator = mongoOperations.getCollection(collection).find(query, projection).iterator(); while (iterator.hasNext()) { final DBObject object = iterator.next(); final String variantId = (String) object.get(ID); final BasicDBList dbAnnotations = (BasicDBList) object.get(ANNOTATION_FIELD); if (dbAnnotations != null && !dbAnnotations.isEmpty()) { final DBObject dbAnnotation = (DBObject) dbAnnotations.get(0); storedVariantAnnotations.put(variantId, convertToVariantAnnotation(dbAnnotation)); } } return storedVariantAnnotations; }
Source:
public boolean isFeatureEnabled(final Feature feature) { try { return featuresCache.getCurrentData(PREFIX + "/" + feature.getId()) != null; } catch (final Exception e) { LOG.warn("Error occurred when checking if feature '" + feature.getId() + "' is toggled", e); return false; } }

Target:
public boolean isFeatureEnabled(final Feature feature) { try { return featuresCache.getCurrentData(getPath(feature)) != null; } catch (final Exception e) { LOG.warn("Error occurred when checking if feature '" + feature.getId() + "' is toggled", e); return false; } }
Source:
public <T> Mono<CosmosAsyncItemResponse<T>> createItem(T item, CosmosItemRequestOptions options) { if (options == null) { options = new CosmosItemRequestOptions(); } @SuppressWarnings("unchecked") Class<T> itemType = (Class<T>) item.getClass(); RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options); return database.getDocClientWrapper() .createDocument(getLink(), item, requestOptions, true) .map(response -> ModelBridgeInternal.createCosmosAsyncItemResponse(response, itemType, getItemDeserializerWithoutDecryption())) .single(); }

Target:
public <T> Mono<CosmosItemResponse<T>> createItem(T item, CosmosItemRequestOptions options) { if (options == null) { options = new CosmosItemRequestOptions(); } @SuppressWarnings("unchecked") Class<T> itemType = (Class<T>) item.getClass(); RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options); return database.getDocClientWrapper() .createDocument(getLink(), item, requestOptions, true) .map(response -> ModelBridgeInternal.createCosmosAsyncItemResponse(response, itemType, getItemDeserializer())) .single(); }
Source:
public String processSubmit(@ModelAttribute("sample") Sample sample, ModelMap model, SessionStatus session) throws IOException, MalformedSampleException { if (sample instanceof DetailedSampleBuilder) { DetailedSampleBuilder builder = (DetailedSampleBuilder) sample; builder.setSampleClass(sampleClassService.get(builder.getSampleClass().getId())); if (builder.getTissueClass() != null) { builder.setTissueClass(sampleClassService.get(builder.getTissueClass().getId())); } sample = builder.build(new InferStockFromAliquot() { @Override public SampleClass infer(SampleClass sampleClass) { return sampleClassService.inferStockFromAliquot(sampleClass); } }); } try { if (sample.getId() == Sample.UNSAVED_ID) { sampleService.create(sample); } else { sampleService.update(sample); } session.setComplete(); model.clear(); return "redirect:/miso/sample/" + sample.getId(); } catch (IOException ex) { log.debug("Failed to save sample", ex); throw ex; } }

Target:
public String processSubmit(@ModelAttribute("sample") Sample sample, ModelMap model, SessionStatus session) throws IOException, MalformedSampleException { if (sample instanceof DetailedSampleBuilder) { DetailedSampleBuilder builder = (DetailedSampleBuilder) sample; builder.setSampleClass(sampleClassService.get(builder.getSampleClass().getId())); if (builder.getTissueClass() != null) { builder.setTissueClass(sampleClassService.get(builder.getTissueClass().getId())); } if (builder.getParent() == null && builder.getSampleClass().getSampleCategory().equals(SampleAliquot.CATEGORY_NAME)) { builder.setStockClass(sampleClassService.inferStockFromAliquot(builder.getSampleClass())); } sample = builder.build(); } try { if (sample.getId() == Sample.UNSAVED_ID) { sampleService.create(sample); } else { sampleService.update(sample); } session.setComplete(); model.clear(); return "redirect:/miso/sample/" + sample.getId(); } catch (IOException ex) { log.debug("Failed to save sample", ex); throw ex; } }
Source:
private List<MenuItem> findMenusInternal(final Menu menu, final Matcher<MenuItem> matcher, final boolean recursive) { LinkedHashSet<MenuItem> result = new LinkedHashSet<MenuItem>(); if (menu != null) { MenuItem[] items = menu.getItems(); for (MenuItem menuItem : items) { if (menuItem.isDisposed() || isSeparator(menuItem)) { continue; } boolean matches = matcher.matches(menuItem); if (matches) { menuItem.notifyListeners(SWT.Arm, createEvent(menuItem)); Menu subMenu = menuItem.getMenu(); if (subMenu != null) { subMenu.notifyListeners(SWT.Show, createEvent(subMenu)); } result.add(menuItem); } if (recursive) { Menu subMenu = menuItem.getMenu(); if (subMenu != null) { if (!matches) { menuItem.notifyListeners(SWT.Arm, createEvent(menuItem)); subMenu.notifyListeners(SWT.Show, createEvent(subMenu)); } List<MenuItem> menuItems = findMenusInternal(subMenu, matcher, recursive); if (!menuItems.isEmpty()) { result.addAll(menuItems); } else { subMenu.notifyListeners(SWT.Hide, createEvent(subMenu)); } } } } } return new ArrayList<MenuItem>(result); }

Target:
private List<MenuItem> findMenusInternal(final Menu menu, final Matcher<MenuItem> matcher, final boolean recursive) { LinkedHashSet<MenuItem> result = new LinkedHashSet<MenuItem>(); if (menu != null) { MenuItem[] items = menu.getItems(); for (MenuItem menuItem : items) { if (menuItem.isDisposed() || isSeparator(menuItem)) { continue; } boolean matches = matcher.matches(menuItem); if (matches) { menuItem.notifyListeners(SWT.Arm, createEvent(menuItem)); Menu subMenu = menuItem.getMenu(); if (subMenu != null) { subMenu.notifyListeners(SWT.Show, createEvent(subMenu)); } result.add(menuItem); } if (recursive) { Menu subMenu = menuItem.getMenu(); if (subMenu != null) { if (!matches) { menuItem.notifyListeners(SWT.Arm, createEvent(menuItem)); subMenu.notifyListeners(SWT.Show, createEvent(subMenu)); } List<MenuItem> menuItems = findMenusInternal(subMenu, matcher, recursive); if (!menuItems.isEmpty()) { result.addAll(menuItems); } else if (!matches) { subMenu.notifyListeners(SWT.Hide, createEvent(subMenu)); } } } } } return new ArrayList<MenuItem>(result); }
Source:
private void acceptTOSAndPrivacyPolicy(User user) { if (user.getTOSVersion() != CURRENT_TOS_VERSION) { user.setTOSVersion(CURRENT_TOS_VERSION); user.setTOSVersionAcceptanceDate(new Date()); } if (user.getPrivacyPolicyVersion() != CURRENT_PRIVACY_POLICY_VERSION) { user.setPrivacyPolicyVersion(CURRENT_PRIVACY_POLICY_VERSION); user.setPrivacyPolicyVersionAcceptanceDate(new Date()); } }

Target:
private void acceptTOSAndPrivacyPolicy(User user) { Date date = new Date(); if (user.getTOSVersion() != CURRENT_TOS_VERSION) { user.setTOSVersion(CURRENT_TOS_VERSION); user.setTOSVersionAcceptanceDate((date)); } if (user.getPrivacyPolicyVersion() != CURRENT_PRIVACY_POLICY_VERSION) { user.setPrivacyPolicyVersion(CURRENT_PRIVACY_POLICY_VERSION); user.setPrivacyPolicyVersionAcceptanceDate(date); } }
Source:
public void runTask() { JobConfig jobConfig = new JobConfig(this.config); String taskName = new TaskConfig(config).getTaskClass().get(); if (taskName == null) { throw new SamzaException("Neither APP nor task.class are defined defined"); } LOG.info("LocalApplicationRunner will run " + taskName); try { LOG.info("Starting job with config {}", jobConfig.getName(), jobConfig); JobRunner runner = new JobRunner(jobConfig); runner.run(true); } catch (Throwable t) { throw new SamzaException("Failed to runTask() application", t); } }

Target:
public void runTask() { throw new UnsupportedOperationException("Running StreamTask is not implemented for RemoteReplicationRunner"); }
Source:
protected Boolean doInBackground(Void... nada) { if (mIsPage) { tmpPosts = mPostStore.getPagesForSite(mSite); } else { tmpPosts = mPostStore.getPostsForSite(mSite); } for (PostModel hiddenPost : mHiddenPosts) { tmpPosts.remove(hiddenPost); } if (mLoadMode == LoadMode.IF_CHANGED && PostUtils.postListsAreEqual(mPosts, tmpPosts)) { boolean postsAreUploading = false; for (PostModel post : tmpPosts) { if (PostUploadService.isPostUploading(post)) { postsAreUploading = true; break; } } if (!postsAreUploading) { return false; } } mFeaturedImageUrls.clear(); for (PostModel post : tmpPosts) { String imageUrl = null; if (post.getFeaturedImageId() != 0) { MediaModel media = mMediaStore.getSiteMediaWithId(mSite, post.getFeaturedImageId()); if (media != null) { imageUrl = media.getUrl(); } else { mediaIdsToUpdate.add(post.getFeaturedImageId()); } } else { imageUrl = new ReaderImageScanner(post.getContent(), mSite.isPrivate()).getLargestImage(); } if (!TextUtils.isEmpty(imageUrl)) { mFeaturedImageUrls.put(post.getId(), imageUrl); } } return true; }

Target:
protected Boolean doInBackground(Void... nada) { if (mIsPage) { tmpPosts = mPostStore.getPagesForSite(mSite); } else { tmpPosts = mPostStore.getPostsForSite(mSite); } for (PostModel hiddenPost : mHiddenPosts) { tmpPosts.remove(hiddenPost); } if (mLoadMode == LoadMode.IF_CHANGED && PostUtils.postListsAreEqual(mPosts, tmpPosts)) { boolean postsAreUploading = false; for (PostModel post : tmpPosts) { if (PostUploadService.isPostUploading(post)) { postsAreUploading = true; break; } } if (!postsAreUploading) { return false; } } mFeaturedImageUrls.clear(); boolean isPrivate = !SiteUtils.isPhotonCapable(mSite); for (PostModel post : tmpPosts) { String imageUrl = null; if (post.getFeaturedImageId() != 0) { MediaModel media = mMediaStore.getSiteMediaWithId(mSite, post.getFeaturedImageId()); if (media != null) { imageUrl = media.getUrl(); } else { mediaIdsToUpdate.add(post.getFeaturedImageId()); } } else { imageUrl = new ReaderImageScanner(post.getContent(), isPrivate).getLargestImage(); } if (!TextUtils.isEmpty(imageUrl)) { mFeaturedImageUrls.put(post.getId(), imageUrl); } } return true; }
Source:
public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } if (!names.contains(name)) { File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED); if (dir != null) { if (dir.getName().equals(name.get() + Constants.DOT_GIT_EXT)) { onCreateProject(name); } else { throw new RepositoryNotFoundException(gitDirOf(name)); } } else { throw new RepositoryNotFoundException(gitDirOf(name)); } } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }

Target:
public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } if (!names.contains(name)) { list(); if (names.contains(name)) { onCreateProject(name); } else { throw new RepositoryNotFoundException(gitDirOf(name)); } } final FileKey loc = FileKey.lenient(gitDirOf(name), FS.DETECTED); try { return RepositoryCache.open(loc); } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot open repository " + name); e2.initCause(e1); throw e2; } }
Source:
@Override public Response<T> execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already executed"); executed = true; } if (canceled) { throw new InterruptedIOException("canceled"); } Future<Response<T>> task = backgroundExecutor.submit(new Callable<Response<T>>() { @Override public Response<T> call() throws Exception { try { if (behavior.calculateIsFailure()) { throw behavior.failureException(); } Response<T> response = delegate.execute(); Thread.sleep(behavior.calculateDelay(MILLISECONDS)); return response; } catch (IOException | RuntimeException e) { Thread.sleep(behavior.calculateDelay(MILLISECONDS)); throw e; } } }); this.task = task; try { return task.get(); } catch (CancellationException | InterruptedException e) { throw new InterruptedIOException("canceled"); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof IOException) { throw (IOException) cause; } throw new IllegalStateException(cause); } }

Target:
@Override public Response<T> execute() throws IOException { final AtomicReference<Response<T>> responseRef = new AtomicReference<>(); final AtomicReference<Throwable> failureRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); enqueue(new Callback<T>() { @Override public void onResponse(Response<T> response) { responseRef.set(response); latch.countDown(); } @Override public void onFailure(Throwable t) { failureRef.set(t); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { throw new InterruptedIOException("canceled"); } Response<T> response = responseRef.get(); if (response != null) return response; Throwable failure = failureRef.get(); if (failure instanceof RuntimeException) throw (RuntimeException) failure; if (failure instanceof IOException) throw (IOException) failure; throw new RuntimeException(failure); }
Source:
private void placeIdentityDisks(List<Coordinate> startingCoordinates, Map<Coordinate, Coordinate> teleporters, int maxX, int maxY) { int numberOfToPlaceIdentityDisks = (int) Math.ceil(builder.getNumberOfSquares() * PERCENTAGE_OF_IDENTITY_DISKS); Set<Coordinate> placedIdentityDisksCoordinates = new HashSet<Coordinate>(); Random rand = new Random(); for (Coordinate startCoord : startingCoordinates) { Coordinate position = null; do { int x = startCoord.getX() - 4 + rand.nextInt(9); int y = startCoord.getY() - 4 + rand.nextInt(9); position = new Coordinate(x, y); } while (!builder.canPlaceItem(position) || placedIdentityDisksCoordinates.contains(position) || startingCoordinates.contains(position)); builder.placeUnchargedIdentityDisc(position); placedIdentityDisksCoordinates.add(position); } while (placedIdentityDisksCoordinates.size() < numberOfToPlaceIdentityDisks) { Coordinate position = Coordinate.random(maxX + 1, maxY + 1); if (builder.canPlaceItem(position) && !placedIdentityDisksCoordinates.contains(position)) { builder.placeUnchargedIdentityDisc(position); placedIdentityDisksCoordinates.add(position); } } placedCharchedIDdisks(startingCoordinates, teleporters); }

Target:
private void placeIdentityDisks(List<Coordinate> startingCoordinates, Map<Coordinate, Coordinate> teleporters, int maxX, int maxY) { int numberOfIdentityDisksToPlace = (int) Math.ceil(builder.getNumberOfSquares() * PERCENTAGE_OF_IDENTITY_DISKS); Set<Coordinate> placedIdentityDisksCoordinates = new HashSet<Coordinate>(); Random rand = new Random(); for (Coordinate startCoord : startingCoordinates) { Coordinate position = null; do { int x = startCoord.getX() - 4 + rand.nextInt(9); int y = startCoord.getY() - 4 + rand.nextInt(9); position = new Coordinate(x, y); } while (!builder.canPlaceItem(position) || placedIdentityDisksCoordinates.contains(position) || startingCoordinates.contains(position)); builder.placeUnchargedIdentityDisc(position); placedIdentityDisksCoordinates.add(position); } while (placedIdentityDisksCoordinates.size() < numberOfIdentityDisksToPlace) { Coordinate position = Coordinate.random(maxX + 1, maxY + 1); if (builder.canPlaceItem(position) && !placedIdentityDisksCoordinates.contains(position)) { builder.placeUnchargedIdentityDisc(position); placedIdentityDisksCoordinates.add(position); } } placedCharchedIDdisks(startingCoordinates, teleporters); }
Source:
public ScannerRunner(List<JavaFileScanner> executableScanners) { checks = new EnumMap<>(Tree.Kind.class); subscriptionVisitors = executableScanners.stream() .filter(s -> s instanceof IssuableSubscriptionVisitor) .map(s -> (SubscriptionVisitor) s).collect(Collectors.toList()); subscriptionVisitors.forEach(s -> s.nodesToVisit().forEach(k -> { if (!checks.containsKey(k)) { checks.put(k, new ArrayList<>()); } checks.get(k).add(s); }) ); }

Target:
ScannerRunner(List<JavaFileScanner> executableScanners) { checks = new EnumMap<>(Tree.Kind.class); subscriptionVisitors = executableScanners.stream() .filter(isIssuableSubscriptionVisitor) .map(s -> (SubscriptionVisitor) s) .collect(Collectors.toList()); subscriptionVisitors.forEach(s -> s.nodesToVisit().forEach(k -> checks.computeIfAbsent(k, key -> new ArrayList<>()).add(s)) ); }
Source:
public List<File> filterFiles(File[] files) { List<File> list = new ArrayList<>(); for (File file : files) { if (file.lastModified() / ONE_SECOND + this.age <= System.currentTimeMillis() / ONE_SECOND) { list.add(file); } else if (this.discardCallback != null) { this.discardCallback.accept(file); } } return list; }

Target:
public List<File> filterFiles(File[] files) { List<File> list = new ArrayList<>(); long now = System.currentTimeMillis() / ONE_SECOND; for (File file : files) { if (fileIsAged(file, now)) { list.add(file); } else if (this.discardCallback != null) { this.discardCallback.accept(file); } } return list; }
Source:
public void updated(Dictionary config) throws ConfigurationException { if (config != null) { Slack.authToken = (String) config.get("authToken"); if (StringUtils.isBlank(Slack.authToken)) { throw new ConfigurationException("slack", "Parameter authToken is mandatory and must be configured. Please check your slack.cfg!"); } isProperlyConfigured = true; } }

Target:
public void updated(Dictionary config) throws ConfigurationException { if (config != null) { Slack.authToken = (String) config.get("authToken"); if (StringUtils.isBlank(Slack.authToken)) { throw new ConfigurationException("slack", "Parameter authToken is mandatory and must be configured. Please check your configuration!"); } isProperlyConfigured = true; } }
Source:
public PyClassDefTree classDefStatement(AstNode astNode) { PyNameTree name = name(astNode.getFirstChild(PythonGrammar.CLASSNAME).getFirstChild(PythonGrammar.NAME)); PyArgListTree args = null; AstNode argList = astNode.getFirstChild(PythonGrammar.ARGLIST); if(argList!=null) { List<PyArgumentTree> arguments = argList(argList); args = new PyArgListTreeImpl(argList, arguments); } PyStatementListTree body = getStatementListFromSuite(astNode.getFirstChild(PythonGrammar.SUITE)); return new PyClassDefTreeImpl(astNode, name, args, body, DocstringExtractor.extractDocstring(astNode)); }

Target:
public PyClassDefTree classDefStatement(AstNode astNode) { PyNameTree name = name(astNode.getFirstChild(PythonGrammar.CLASSNAME).getFirstChild(PythonGrammar.NAME)); PyArgListTree args = null; AstNode leftPar = astNode.getFirstChild(PythonPunctuator.LPARENTHESIS); if (leftPar != null) { AstNode argList = astNode.getFirstChild(PythonGrammar.ARGLIST); List<PyArgumentTree> arguments = argList(argList); args = new PyArgListTreeImpl(argList, arguments); } PyStatementListTree body = getStatementListFromSuite(astNode.getFirstChild(PythonGrammar.SUITE)); return new PyClassDefTreeImpl(astNode, name, args, body, DocstringExtractor.extractDocstring(astNode)); }
Source:
private String readString(ByteBuffer input) { int nicknameLength = (int)input.get(); if (nicknameLength > 0) { char[] nickname = new char[nicknameLength]; for (int i = 0; i < nickname.length; ++i) { nickname[i] = (char)(input.get()); } return new String(nickname); } else { return new String(); } }

Target:
private String readString(ByteBuffer input) { int stringLength = (int)input.get(); if (stringLength > 0) { char[] string = new char[stringLength]; for (int i = 0; i < string.length; ++i) { string[i] = (char)(input.get()); } return new String(string); } else { return new String(); } }
Source:
public void onStateUpdateFromItem(State state) { callback.handleUpdate(state); }

Target:
public void onStateUpdateFromItem(State state) { if (!(state instanceof Command)) { logger.debug("The given state could not be transformed to a command", state); return; } Command command = (Command) state; callback.handleCommand(command); }
Source:
public ScalebarDrawer(final Graphics2D graphics2d, final ScaleBarRenderSettings settings) { this.graphics2d = graphics2d; this.transform = graphics2d.getTransform(); this.settings = settings; this.params = settings.getParams(); }

Target:
public ScalebarDrawer(final Graphics2D graphics2d, final ScaleBarRenderSettings settings) { this.graphics2d = graphics2d; this.transform = new AffineTransform(graphics2d.getTransform()); this.settings = settings; this.params = settings.getParams(); }
Source:
public void setVisible(boolean isVisible) { super.setVisible(isVisible); if (isVisible) { sendOnResizeLocal_.schedule(5); } }

Target:
public void setVisible(boolean isVisible) { super.setVisible(isVisible); if (isVisible) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { onResize(); } }); } }
Source:
public <Intermediate, Final> ListenableFuture<Final> go( Request request, HttpResponseHandler<Intermediate, Final> httpResponseHandler, Duration duration ) { if (requestNum++ == 0) { throw new RuntimeException("simulating couldn't send request to server for some reason."); } if (requestNum++ == 1) { HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse); return Futures.immediateFailedFuture(new RuntimeException("server error")); } HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse); try { return results.take(); } catch (InterruptedException ex) { throw new RE(ex, "Interrupted."); } }

Target:
public <Intermediate, Final> ListenableFuture<Final> go( Request request, HttpResponseHandler<Intermediate, Final> httpResponseHandler, Duration duration ) { if (requestNum.getAndIncrement() == 0) { throw new RuntimeException("simulating couldn't send request to server for some reason."); } if (requestNum.get() == 2) { HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse); return Futures.immediateFailedFuture(new RuntimeException("server error")); } HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse); try { return results.take(); } catch (InterruptedException ex) { throw new RE(ex, "Interrupted."); } }
Source:
public PinotColumnMetadata(String name, Type type, boolean inNullable, String comment) { super(requireNonNull(name, "name is null"), requireNonNull(type, "type is null"), inNullable, comment, null, false, emptyMap()); this.name = name; }

Target:
public PinotColumnMetadata(String name, Type type, boolean inNullable, String comment) { super(requireNonNull(name, "name is null"), requireNonNull(type, "type is null"), inNullable, comment, null, false, ImmutableMap.of()); this.name = name; }
Source:
public List<DeviceData> batchInsertReturnsRemaining(final List<DeviceData> deviceDataList) { final Map<String, List<WriteRequest>> requestItems = toWriteRequestItems(deviceDataList); final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest().withRequestItems(requestItems); final BatchWriteItemResult result = this.dynamoDBClient.batchWriteItem(batchWriteItemRequest); final Map<String, List<WriteRequest>> remainingItems = result.getUnprocessedItems(); final List<DeviceData> remainingData = Lists.newArrayList(); for (final List<WriteRequest> requests : remainingItems.values()) { for (final WriteRequest request: requests) { final Map<String, AttributeValue> item = request.getPutRequest().getItem(); if (item != null && !item.isEmpty()) { remainingData.add(dynamoItemToDeviceData(item)); } } } return remainingData; }

Target:
public List<DeviceData> batchInsertReturnsRemaining(final List<DeviceData> deviceDataList) { final List<Map<String, AttributeValue>> remainingItems = batchInsertNoRetryReturnsRemaining(deviceDataList); final List<DeviceData> remainingDeviceData = Lists.newArrayListWithCapacity(remainingItems.size()); for (final Map<String, AttributeValue> item : remainingItems) { remainingDeviceData.add(dynamoItemToRawDeviceData(item)); } return remainingDeviceData; }
Source:
public void testAdd() { Entity e = Mockito.mock(Entity.class); field.add(e); assertSame(e, field.getEntities().get(1)); assertSame(e, field.getDrawables().getFirst()); assertEquals(2, field.getDrawables().size()); }

Target:
public void testAdd() { Entity e = Mockito.mock(Entity.class); field.add(e); assertTrue(field.getEntities().contains(e)); assertSame(e, field.getDrawables().getFirst()); assertEquals(2, field.getDrawables().size()); }
Source:
public boolean belongsTo(Object family) { return (this.family == null || family == null) ? false : this.family.equals(family); }

Target:
public boolean belongsTo(Object family) { return Objects.equals(this.family, family); }
Source:
protected String getManagementRealm(String url) throws IOException { CloseableHttpClient defaultHttpClient = HttpClients.custom() .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultRequestConfig(requestConfig) .build(); HttpPost post = new HttpPost(url); post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); CloseableHttpResponse response = null; try { response = defaultHttpClient.execute(post); } finally { defaultHttpClient.close(); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_UNAUTHORIZED) { throw new IllegalStateException(String.format("Server responded with %d instead of %d after first request.", response.getStatusLine().getStatusCode(), HttpStatus.SC_UNAUTHORIZED)); } if (!response.containsHeader(HttpHeaders.WWW_AUTHENTICATE)) { throw new IllegalStateException("Missing WWW-Authenticate header in server response after first request."); } for (HeaderElement el : response.getHeaders(HttpHeaders.WWW_AUTHENTICATE)[0].getElements()) { if (el.getName().equals("Digest realm")) { return el.getValue(); } } throw new IllegalStateException("Digest realm not found in in WWW-Authenticate header."); }

Target:
private String getManagementRealm(String url) throws IOException { CloseableHttpClient defaultHttpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .build(); HttpPost post = new HttpPost(url); post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); CloseableHttpResponse response = null; try { response = defaultHttpClient.execute(post); response.close(); } finally { defaultHttpClient.close(); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_UNAUTHORIZED) { throw new IllegalStateException(String.format("Server responded with %d instead of %d after first request.", response.getStatusLine().getStatusCode(), HttpStatus.SC_UNAUTHORIZED)); } if (!response.containsHeader(HttpHeaders.WWW_AUTHENTICATE)) { throw new IllegalStateException("Missing WWW-Authenticate header in server response after first request."); } for (HeaderElement el : response.getHeaders(HttpHeaders.WWW_AUTHENTICATE)[0].getElements()) { if (el.getName().equals("Digest realm")) { return el.getValue(); } } throw new IllegalStateException("Digest realm not found in WWW-Authenticate header."); }