auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void enableValueNotifications(Consumer<byte[]> callback) throws KuraBluetoothNotificationException { try { DeviceManager.getInstance().registerPropertyHandler(new AbstractPropertiesChangedHandler() { @Override public void handle(PropertiesChanged props) { if (props != null) { if (!props.getPath().contains(BluetoothLeGattCharacteristicImpl.this.characteristic.getDbusPath())) { return; } for (Map.Entry<String, Variant<?>> entry : props.getPropertiesChanged().entrySet()) { if (entry.getKey().equals("Value")) { Object obj = entry.getValue().getValue(); byte[] val = (byte[]) obj; callback.accept(val); } } } } }); this.characteristic.startNotify(); } catch (DBusException e) { throw new KuraBluetoothNotificationException(e, "Notification can't be enabled"); } }

Target:
public void enableValueNotifications(Consumer<byte[]> callback) throws KuraBluetoothNotificationException { try { DeviceManager.getInstance().registerPropertyHandler(new AbstractPropertiesChangedHandler() { @Override public void handle(PropertiesChanged props) { if (props != null) { if (!props.getPath().contains(BluetoothLeGattCharacteristicImpl.this.characteristic.getDbusPath())) { return; } for (Map.Entry<String, Variant<?>> entry : props.getPropertiesChanged().entrySet()) { if (entry.getKey().equals("Value")) { byte[] value = (byte[]) props.getPropertiesChanged().get("Value").getValue(); if (value != null) { callback.accept(value); } } } } } }); this.characteristic.startNotify(); } catch (DBusException e) { throw new KuraBluetoothNotificationException(e, "Notification can't be enabled"); } }
Source:
public NettyByteBufLeakHelper() { cachedEnabled = Integer.parseInt(System.getProperty("io.netty.alllocator.maxCachedBufferCapacity", "0")) != 0; }

Target:
public NettyByteBufLeakHelper() { cachedEnabled = Integer.parseInt(System.getProperty("io.netty.allocator.maxCachedBufferCapacity", "0")) != 0; }
Source:
public TestClasspathRegistry(Set<TestClasspathProvider> testClasspathProviders) { System.out.println("inititilaized TestClasspathRegistry " + testClasspathProviders.size() + " wkwkwkwkwk " + testClasspathProviders.toString()); testClasspathProviders.forEach(this::register); }

Target:
public TestClasspathRegistry(Set<TestClasspathProvider> testClasspathProviders) { testClasspathProviders.forEach(this::register); }
Source:
public void getResourcesInformation(final IDMContext dmc, final String resourceClass, final DataRequestMonitor<IResourcesInformation> rm) { getExecutor().submit(new DsfRunnable() { @Override public void run() { IGDBControl control = getServicesTracker().getService(IGDBControl.class); control.queueCommand(new MIInfoOs(dmc, resourceClass), new DataRequestMonitor<MIInfoOsInfo>(getExecutor(), rm) { @Override protected void handleCompleted() { rm.setData(getData().getResourcesInformation()); super.handleCompleted(); } }); } }); }

Target:
public void getResourcesInformation(final IDMContext dmc, final String resourceClass, final DataRequestMonitor<IResourcesInformation> rm) { IGDBControl control = getServicesTracker().getService(IGDBControl.class); CommandFactory factory = control.getCommandFactory(); control.queueCommand(factory.createMIInfoOS(dmc, resourceClass), new DataRequestMonitor<MIInfoOsInfo>(getExecutor(), rm) { @Override protected void handleSuccess() { rm.setData(getData().getResourcesInformation()); rm.done(); } }); }
Source:
private void flushAndCheckpointState() { try { stateMgr.flush(); } catch (final ProcessorStateException e) { if (e.getCause() instanceof ProducerFencedException) { log.warn("Caught a retriable Kafka exception while flushing state. Initiating a rebalance to attempt recovery.", e); throw new TaskMigratedException(this, e); } } stateMgr.checkpoint(Collections.emptyMap()); }

Target:
private void flushAndCheckpointState() { stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); }
Source:
public void testSingleCast() { Single<?> source = Single.just(1); Single<Integer> single = source.cast(Integer.class); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); single.subscribe(observer); verify(observer, times(1)).onNext(1); verify(observer, times(1)).onNext(1); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); }

Target:
public void testSingleCast() { Single<?> source = Single.just(1); Single<Integer> single = source.cast(Integer.class); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); single.subscribe(observer); verify(observer, times(1)).onNext(1); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); }
Source:
private void processAttrs(AttributeSet attrs) { if (attrs != null) { mUseParentLayoutParams = attrs.getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.useParentLayoutParams, true); mLayoutManagerOrientationString = attrs.getAttributeValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerOrientation); mRtlLayout = attrs.getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerReverse, mRtlLayout); mSpanCount = attrs.getAttributeIntValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerSpanCount, 1); mInitialPrefetchCount = attrs.getAttributeIntValue(null, BindingResources.attr.BindableRecyclerView.initialPrefetchCount, 0); mLayoutManagerType = attrs.getAttributeValue(null, BindingResources.attr.BindableRecyclerView.layoutManager); Boolean nestedScrollingEnabled = attrs .getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.nestedScrollingEnabled, isNestedScrollingEnabled()); if (nestedScrollingEnabled != isNestedScrollingEnabled()) { setNestedScrollingEnabled(nestedScrollingEnabled); } } }

Target:
private void processAttrs(AttributeSet attrs) { if (attrs != null) { mUseParentLayoutParams = attrs.getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.useParentLayoutParams, true); mLayoutManagerOrientationString = attrs.getAttributeValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerOrientation); mRtlLayout = attrs.getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerReverse, mRtlLayout); mSpanCount = attrs.getAttributeIntValue(null, BindingResources.attr.BindableRecyclerView.layoutManagerSpanCount, 1); mInitialPrefetchCount = attrs.getAttributeIntValue(null, BindingResources.attr.BindableRecyclerView.initialPrefetchCount, 0); mLayoutManagerType = attrs.getAttributeValue(null, BindingResources.attr.BindableRecyclerView.layoutManager); boolean nestedScrollingEnabled = attrs .getAttributeBooleanValue(null, BindingResources.attr.BindableRecyclerView.nestedScrollingEnabled, isNestedScrollingEnabled()); if (nestedScrollingEnabled != isNestedScrollingEnabled()) { setNestedScrollingEnabled(nestedScrollingEnabled); } } }
Source:
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay readerWay, EncodingManager.Access access, long relationFlags) { if (readerWay.hasTag("toll", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.ALL); if (readerWay.hasTag("toll:hgv", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.HGV); return edgeFlags; }

Target:
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay readerWay, EncodingManager.Access access, long relationFlags) { if (readerWay.hasTag("toll", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.ALL); else if (readerWay.hasTag("toll:hgv", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.HGV); return edgeFlags; }
Source:
private void unregisterAndCloseRepository(final Key location, Repository db) { synchronized (lockFor(location)) { if (isExpired(db)) { Repository oldDb = unregisterRepository(location); if (oldDb != null) { oldDb.doClose(); } } } }

Target:
private void unregisterAndCloseRepository(final Key location, Repository db) { synchronized (lockFor(location)) { Repository oldDb = unregisterRepository(location); if (oldDb != null) { oldDb.doClose(); } } }
Source:
default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) { return reduceLeft(op); }

Target:
default T reduceRight(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); return get(); }
Source:
private void logConflictOverridesIfEnabled(String[] overrideConflicts) { if (log.isDebugEnabled()) { for (String s : overrideConflicts) { log.debug("Forcing conflict if encountered: " + s); } } }

Target:
private void logConflictOverridesIfEnabled(String[] overrideConflicts) { if (log.isDebugEnabled()) { for (String s : overrideConflicts) { log.debug("Forcing conflict if encountered: {}", s); } } }
Source:
private void handleEmbed(EmbedEvent event) { String mimeType = event.mimeType; if(mimeType.startsWith("text/")) { if (event.name != null) { jsFunctionCall("embedding", mimeType, new String(event.data), event.name); } else { jsFunctionCall("embedding", mimeType, new String(event.data)); } } else { String extension = MIME_TYPES_EXTENSIONS.get(mimeType); if (extension != null) { StringBuilder fileName = new StringBuilder("embedded").append(embeddedIndex++).append(".").append(extension); writeBytesToURL(event.data, toUrl(fileName.toString())); if (event.name != null) { jsFunctionCall("embedding", mimeType, fileName, event.name); } else { jsFunctionCall("embedding", mimeType, fileName); } } } }

Target:
private void handleEmbed(EmbedEvent event) { String mimeType = event.mimeType; if(mimeType.startsWith("text/")) { jsFunctionCall("embedding", mimeType, new String(event.data), event.name); } else { String extension = MIME_TYPES_EXTENSIONS.get(mimeType); if (extension != null) { StringBuilder fileName = new StringBuilder("embedded").append(embeddedIndex++).append(".").append(extension); writeBytesToURL(event.data, toUrl(fileName.toString())); jsFunctionCall("embedding", mimeType, fileName, event.name); } } }
Source:
public void releaseImageReaderListWhenDeatached() { mDeferredImageReaderSurface.refresh(); mDeferredImageReaderSurface.notifySurfaceAttached(); mDeferredImageReaderSurface.refresh(); mDeferredImageReaderSurface.notifySurfaceAttached(); assertThat(mDeferredImageReaderSurface.mImageReaderToReleaseList.size()) .isEqualTo(2); mDeferredImageReaderSurface.notifySurfaceDetached(); assertThat(mDeferredImageReaderSurface.getAttachedCount()) .isEqualTo(2); assertThat(mDeferredImageReaderSurface.getSurface()).isNotNull(); assertThat(mDeferredImageReaderSurface.mImageReaderToReleaseList.size()) .isEqualTo(0); }

Target:
public void releaseImageReaderListWhenDeatached() { mDeferredImageReaderSurface.refresh(); mDeferredImageReaderSurface.notifySurfaceAttached(); mDeferredImageReaderSurface.refresh(); mDeferredImageReaderSurface.notifySurfaceAttached(); assertThat(mDeferredImageReaderSurface.mImageReaderToReleaseList.size()) .isEqualTo(2); mDeferredImageReaderSurface.notifySurfaceDetached(); assertThat(mDeferredImageReaderSurface.getAttachedCount()).isEqualTo(2); assertThat(mDeferredImageReaderSurface.mImageReaderToReleaseList.size()) .isEqualTo(0); assertThat(mDeferredImageReaderSurface.getImageReader()).isNotNull(); }
Source:
public void iSetUpADriverToAnIncorrectPort() throws Throwable { try ( Driver driver = GraphDatabase.driver( "bolt://localhost:" + getFreePort() ); Session session = driver.session() ) { session.run( "RETURN 1" ); } catch ( Exception e ) { exception = e; } }

Target:
public void iSetUpADriverToAnIncorrectPort() throws Throwable { try ( Driver driver = GraphDatabase.driver( "bolt://localhost:777" ); Session session = driver.session() ) { session.run( "RETURN 1" ); } catch ( Exception e ) { exception = e; } }
Source:
protected void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_widget_config); Intent configIntent = getIntent(); Bundle extras = configIntent.getExtras(); if(extras != null){ appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetId); setResult(RESULT_CANCELED,resultValue); if(appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){ finish(); } opacityTextview = findViewById(R.id.widget_opacity_textView); opacitySeekbar = findViewById(R.id.widget_opacity_seekBar); opacitySeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { opacityTextview.setText(seekBar.getProgress() + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_widget_config); Intent configIntent = getIntent(); Bundle extras = configIntent.getExtras(); if (extras != null) { appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); setResult(RESULT_CANCELED, resultValue); if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); } displayDeviceBackground(); opacityTextView = findViewById(R.id.widget_opacity_textView); opacitySeekBar = findViewById(R.id.widget_opacity_seekBar); widgetPreview = findViewById(R.id.widgetLayout); findViewById(R.id.butConfirm).setOnClickListener(this::confirmCreateWidget); opacitySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { opacityTextView.setText(seekBar.getProgress() + "%"); int color = getColorWithAlpha(PlayerWidget.DEFAULT_COLOR, opacitySeekBar.getProgress()); widgetPreview.setBackgroundColor(color); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }
Source:
public TypeInfo visit(CharType charType) { if (charType.getLength() > HiveChar.MAX_CHAR_LENGTH || charType.getLength() < 1) { if (checkPrecision) { throw new CatalogException( String.format("HiveCatalog doesn't support char type with length of '%d'. " + "The maximum length is %d", charType.getLength(), HiveChar.MAX_CHAR_LENGTH)); } else { return TypeInfoFactory.stringTypeInfo; } } return TypeInfoFactory.getCharTypeInfo(charType.getLength()); }

Target:
public TypeInfo visit(CharType charType) { if (charType.getLength() > HiveChar.MAX_CHAR_LENGTH || charType.getLength() < 1) { if (checkPrecision) { throw new CatalogException( String.format("HiveCatalog doesn't support char type with length of '%d'. " + "The supported length is [%d, %d]", charType.getLength(), 1, HiveChar.MAX_CHAR_LENGTH)); } else { return TypeInfoFactory.stringTypeInfo; } } return TypeInfoFactory.getCharTypeInfo(charType.getLength()); }
Source:
public List<Change.Id> changesReviewedBy(final ReviewDb db, final String userName) { UserNameProcessor processor = new UserNameProcessor(db, userName) { @Override void process(ReviewDb db, Account account, Map<Id, Change> outResultChanges) throws OrmException { ChangeApprovalAccess changes = db.changeApprovals(); ChangeAccess changeAccess = db.changes(); Iterator<ChangeApproval> changeIterator = changes.reviewedByUser(account.getId()).iterator(); while (changeIterator.hasNext()) { ChangeApproval approval = changeIterator.next(); Change change = changeAccess.get(approval.getChangeId()); if (change != null) { outResultChanges.put(change.getId(), change); } } } }; processor.run(); return filterResults(processor.getResult()); }

Target:
private List<Change.Id> changesReviewedBy(final ReviewDb db, final String userName) { UserNameProcessor processor = new UserNameProcessor(db, userName) { @Override void process(ReviewDb db, Account.Id account, Map<Id, Change> outResultChanges) throws OrmException { ChangeApprovalAccess changes = db.changeApprovals(); ChangeAccess changeAccess = db.changes(); Iterator<ChangeApproval> changeIterator = changes.reviewedByUser(account).iterator(); while (changeIterator.hasNext()) { ChangeApproval approval = changeIterator.next(); Change change = changeAccess.get(approval.getChangeId()); if (change != null) { outResultChanges.put(change.getId(), change); } } } }; return new ArrayList<Change.Id>(processor.call()); }
Source:
public void customizedNamesAreBoundCorrectly() throws NoSuchFieldException { db.getJdbi().useHandle(h -> { h.createUpdate("create table enums(id int, name varchar)").execute(); h.createUpdate("insert into enums (id, name) values (1, :name)") .bind("name", Foobar.CUSTOM) .execute(); String ordinal = h.createQuery("select name from enums") .mapTo(String.class) .one(); assertThat(ordinal) .isEqualTo(Foobar.class.getField(Foobar.CUSTOM.name()) .getAnnotation(DatabaseValue.class).value()); }); }

Target:
public void customizedNamesAreBoundCorrectly() throws NoSuchFieldException { db.getJdbi().useHandle(h -> { h.createUpdate("create table enums(id int, name varchar)").execute(); h.createUpdate("insert into enums (id, name) values (1, :name)") .bind("name", Foobar.CUSTOM) .execute(); final String databaseString = h.createQuery("select name from enums") .mapTo(String.class) .one(); assertThat(databaseString) .isEqualTo("CUST"); }); }
Source:
protected PageableResult doSearch(RequestContext context) { String patientUuid = context.getRequest().getParameter("patient"); if (patientUuid != null) { Patient patient = ((PatientResource1_8) Context.getService(RestService.class).getResourceBySupportedClass( Patient.class)).getByUniqueId(patientUuid); if (patient == null) return new EmptySearchResult(); List<Obs> obs = Context.getObsService().getObservationsByPerson(patient); return new NeedsPaging<Obs>(obs, context); } String encounterUuid = context.getRequest().getParameter("encounter"); boolean includeVoided = Boolean.parseBoolean(context.getRequest().getParameter("includeAll")); if (encounterUuid != null) { Encounter enc = ((EncounterResource1_8) Context.getService(RestService.class).getResourceBySupportedClass( Encounter.class)).getByUniqueId(encounterUuid); if (enc == null) return new EmptySearchResult(); if (includeVoided) { List<Obs> obs = new ArrayList<Obs>(enc.getAllObs(includeVoided)); return new NeedsPaging<Obs>(obs, context); } else { List<Obs> obs = new ArrayList<Obs>(enc.getAllObs()); return new NeedsPaging<Obs>(obs, context); } } return new NeedsPaging<Obs>(Context.getObsService().getObservations(context.getParameter("q")), context); }

Target:
protected PageableResult doSearch(RequestContext context) { String patientUuid = context.getRequest().getParameter("patient"); if (patientUuid != null) { Patient patient = ((PatientResource1_8) Context.getService(RestService.class).getResourceBySupportedClass( Patient.class)).getByUniqueId(patientUuid); if (patient == null) return new EmptySearchResult(); List<Obs> obs = Context.getObsService().getObservationsByPerson(patient); return new NeedsPaging<Obs>(obs, context); } String encounterUuid = context.getRequest().getParameter("encounter"); if (encounterUuid != null) { Encounter enc = ((EncounterResource1_8) Context.getService(RestService.class).getResourceBySupportedClass( Encounter.class)).getByUniqueId(encounterUuid); if (enc == null) return new EmptySearchResult(); List<Obs> obs = new ArrayList<Obs>(enc.getAllObs(context.getIncludeAll())); return new NeedsPaging<Obs>(obs, context); } return new NeedsPaging<Obs>(Context.getObsService().getObservations(context.getParameter("q")), context); }
Source:
public void initialise() { setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation()); WidgetUtil.trySubscribe(this, "close", button -> { final UniverseSetupScreen universeSetupScreen = getManager().createScreen(UniverseSetupScreen.ASSET_URI, UniverseSetupScreen.class); final WorldPreGenerationScreen worldPreGenerationScreen = getManager().createScreen(WorldPreGenerationScreen.ASSET_URI, WorldPreGenerationScreen.class); UIText customWorldName = find("customisedWorldName", UIText.class); boolean goBack = false; if (customWorldName.getText().isEmpty()) { getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Name Cannot Be Empty!", "Please add a name for the world"); } else if (customWorldName.getText().equalsIgnoreCase(world.getWorldName().toString())) { goBack = true; } else { boolean worldNameMatchesAnother = false; for (String worldName : universeSetupScreen.worldNames()) { if (worldName.equalsIgnoreCase(customWorldName.getText())) { worldNameMatchesAnother = true; break; } } if (worldNameMatchesAnother == true) { getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Name Already Used!", "Please use a different name for this world"); } else { goBack = true; } } if (goBack == true) { newWorldName = new Name(customWorldName.getText()); world.setWorldName(newWorldName); universeSetupScreen.refreshWorldDropdown(worldsDropdown); worldPreGenerationScreen.setName(newWorldName); triggerBackAnimation(); } }); }

Target:
public void initialise() { setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation()); WidgetUtil.trySubscribe(this, "close", button -> { final UniverseSetupScreen universeSetupScreen = getManager().createScreen(UniverseSetupScreen.ASSET_URI, UniverseSetupScreen.class); final WorldPreGenerationScreen worldPreGenerationScreen = getManager().createScreen(WorldPreGenerationScreen.ASSET_URI, WorldPreGenerationScreen.class); UIText customWorldName = find("customisedWorldName", UIText.class); boolean goBack = false; if (customWorldName.getText().isEmpty()) { getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Name Cannot Be Empty!", "Please add a name for the world"); } else if (customWorldName.getText().equalsIgnoreCase(world.getWorldName().toString())) { goBack = true; } else if (universeSetupScreen.worldNameMatchesAnother(customWorldName.getText())) { getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Name Already Used!", "Please use a different name for this world"); } else { goBack = true; } if (goBack) { newWorldName = new Name(customWorldName.getText()); world.setWorldName(newWorldName); universeSetupScreen.refreshWorldDropdown(worldsDropdown); worldPreGenerationScreen.setName(newWorldName); triggerBackAnimation(); } }); }
Source:
public <T> Map<Path, SortOrder> getValidSortingRules(final Class<T> entityClass, final EntityDictionary dictionary) throws InvalidValueException { Map<Path, SortOrder> returnMap = new LinkedHashMap<>(); for (Map.Entry<String, SortOrder> entry : replaceIdRule(dictionary.getIdFieldName(entityClass)).entrySet()) { String dotSeparatedPath = entry.getKey(); SortOrder order = entry.getValue(); Path path = new Path(entityClass, dictionary, dotSeparatedPath); for (Path.PathElement pathElement : path.getPathElements()) { if (! dictionary.isRelation(pathElement.getType(), pathElement.getFieldName())) { continue; } if (dictionary.getRelationshipType(pathElement.getType(), pathElement.getFieldName()).isToMany()) { throw new InvalidValueException("Cannot sort across a to-many relationship: " + pathElement.getTypeName() + "." + pathElement.getFieldName() ); } } returnMap.put(path, order); } return returnMap; }

Target:
public <T> Map<Path, SortOrder> getValidSortingRules(final Class<T> entityClass, final EntityDictionary dictionary) throws InvalidValueException { Map<Path, SortOrder> returnMap = new LinkedHashMap<>(); for (Map.Entry<String, SortOrder> entry : replaceIdRule(dictionary.getIdFieldName(entityClass)).entrySet()) { String dotSeparatedPath = entry.getKey(); SortOrder order = entry.getValue(); Path path = new Path(entityClass, dictionary, dotSeparatedPath); if (! isValidSortRulePath(path, dictionary)) { throw new InvalidValueException("Cannot sort across a to-many relationship: " + path.getFieldPath()); } returnMap.put(path, order); } return returnMap; }
Source:
protected Composite createToolTipContentArea(Event event, Composite parent) { Composite tooltipComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); tooltipComposite.setLayout(layout); for (SerieEntry entry : fEntries) { StringBuilder text = new StringBuilder().append(entry.id).append(": ").append(entry.value); Composite serieComposite = new Composite(tooltipComposite, SWT.NONE); layout = new GridLayout(); serieComposite.setLayout(layout); Label label = new Label(serieComposite, SWT.NONE); label.setText(text.toString()); label.setBackground(null); GridData gridData = new GridData(); gridData.horizontalIndent = 16; label.setLayoutData(gridData); serieComposite.addPaintListener(e -> { e.gc.setBackground(entry.color); e.gc.fillOval(5, 10, 10, 10); }); } return tooltipComposite; }

Target:
protected Composite createToolTipContentArea(Event event, Composite parent) { Composite tooltipComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); tooltipComposite.setLayout(layout); for (SerieEntry entry : fEntries) { Composite serieComposite = new Composite(tooltipComposite, SWT.NONE); layout = new GridLayout(); serieComposite.setLayout(layout); StringBuilder text = new StringBuilder().append(entry.id).append(": ").append(entry.value); Label label = addSerieLabel(serieComposite); label.setText(text.toString()); serieComposite.addPaintListener(e -> { e.gc.setBackground(entry.color); e.gc.fillOval(5, 10, 10, 10); }); } return tooltipComposite; }
Source:
private Thread createDelayedCloseExecutor() { Thread delayedCloseExecutor = new Thread( () -> { while (!closed) { Long closeTimeNs = null; Boolean dueToShutdownRequest = null; Long idleCloseTimeNs = idleCloseTimeNsHolder.get(); if (idleCloseTimeNs != null) { closeTimeNs = idleCloseTimeNs; dueToShutdownRequest = false; } Long requestedShutdownTimeNs = requestedShutdownTimeNsHolder.get(); if (requestedShutdownTimeNs != null) { if (closeTimeNs == null || requestedShutdownTimeNs - closeTimeNs <= 0) { closeTimeNs = requestedShutdownTimeNs; dueToShutdownRequest = true; } } if (closeTimeNs == null) { log.error( "A bug in EventReceiverFirehose code, " + "either idleCloseTimeNs or requestedShutdownTimeNs should be non-null" ); try { Threads.sleepFor(1, TimeUnit.MINUTES); } catch (InterruptedException ignore) { } continue; } long closeTimeoutNs = closeTimeNs - System.nanoTime(); if (closeTimeoutNs <= 0) { if (dueToShutdownRequest) { log.info("Closing Firehose after a shutdown request"); } else { log.info("Firehose has been idle for %d ms, closing.", maxIdleTimeMillis); } close(); return; } else { try { Threads.sleepFor(closeTimeoutNs, TimeUnit.NANOSECONDS); } catch (InterruptedException ignore) { } } } }, "event-receiver-firehose-closer" ); this.delayedCloseExecutor = delayedCloseExecutor; delayedCloseExecutor.start(); return delayedCloseExecutor; }

Target:
private Thread createDelayedCloseExecutor() { Thread delayedCloseExecutor = new Thread( () -> { while (!closed) { if (idleCloseTimeNs == null && requestedShutdownTimeNs == null) { log.error( "Either idleCloseTimeNs or requestedShutdownTimeNs must be non-null. " + "Please file a bug at <LINK_0>" ); } if (idleCloseTimeNs != null && idleCloseTimeNs - System.nanoTime() <= 0) { log.info("Firehose has been idle for %d ms, closing.", maxIdleTimeMillis); close(); } else if (requestedShutdownTimeNs != null && requestedShutdownTimeNs - System.nanoTime() <= 0) { log.info("Closing Firehose after a shutdown request"); close(); } try { Threads.sleepFor(1, TimeUnit.SECONDS); } catch (InterruptedException ignore) { } } }, "event-receiver-firehose-closer" ); delayedCloseExecutor.setDaemon(true); this.delayedCloseExecutor = delayedCloseExecutor; delayedCloseExecutor.start(); return delayedCloseExecutor; }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } FakeMetric metric = (FakeMetric) obj; return metric.getName() == getName() && metric.getValue() == getValue(); }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof FakeMetric)) return false; FakeMetric other = (FakeMetric) obj; if (metricManager == null) { if (other.metricManager != null) return false; } else if (!metricManager.equals(other.metricManager)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }
Source:
private synchronized MemoryPoolAssignmentsRequest updateAssignments(Iterable<QueryExecution> queries) { ClusterMemoryPool reservedPool = pools.get(RESERVED_POOL); ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); verify(generalPool != null, "generalPool is null"); verify(reservedPool != null, "reservedPool is null"); long version = memoryPoolAssignmentsVersion.incrementAndGet(); if (allAssignmentsHavePropagated(queries)) { if (reservedPool.getAssignedQueries() == 0 && generalPool.getBlockedNodes() > 0) { QueryExecution biggestQuery = null; long maxMemory = -1; for (QueryExecution queryExecution : queries) { if (resourceOvercommit(queryExecution.getSession())) { continue; } long bytesUsed = getQueryMemoryReservation(queryExecution); if (bytesUsed > maxMemory) { biggestQuery = queryExecution; maxMemory = bytesUsed; } } if (biggestQuery != null) { log.warn("Moving query %s to the reserved pool", biggestQuery.getQueryId()); biggestQuery.setMemoryPool(new VersionedMemoryPoolId(RESERVED_POOL, version)); } } } ImmutableList.Builder<MemoryPoolAssignment> assignments = ImmutableList.builder(); for (QueryExecution queryExecution : queries) { assignments.add(new MemoryPoolAssignment(queryExecution.getQueryId(), queryExecution.getMemoryPool().getId())); } return new MemoryPoolAssignmentsRequest(coordinatorId, version, assignments.build()); }

Target:
private synchronized MemoryPoolAssignmentsRequest updateAssignments(Iterable<QueryExecution> queries) { ClusterMemoryPool reservedPool = pools.get(RESERVED_POOL); ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); verify(generalPool != null, "generalPool is null"); verify(reservedPool != null, "reservedPool is null"); long version = memoryPoolAssignmentsVersion.incrementAndGet(); if (allAssignmentsHavePropagated(queries)) { if (reservedPool.getAssignedQueries() == 0 && generalPool.getBlockedNodes() > 0) { QueryExecution biggestQuery = null; long maxMemory = -1; for (QueryExecution queryExecution : queries) { if (resourceOvercommit(queryExecution.getSession())) { continue; } long bytesUsed = getQueryMemoryReservation(queryExecution); if (bytesUsed > maxMemory) { biggestQuery = queryExecution; maxMemory = bytesUsed; } } if (biggestQuery != null) { log.info("Moving query %s to the reserved pool", biggestQuery.getQueryId()); biggestQuery.setMemoryPool(new VersionedMemoryPoolId(RESERVED_POOL, version)); } } } ImmutableList.Builder<MemoryPoolAssignment> assignments = ImmutableList.builder(); for (QueryExecution queryExecution : queries) { assignments.add(new MemoryPoolAssignment(queryExecution.getQueryId(), queryExecution.getMemoryPool().getId())); } return new MemoryPoolAssignmentsRequest(coordinatorId, version, assignments.build()); }
Source:
private static void putBlobPropertiesToBufferV1(ByteBuffer outputBuffer, BlobProperties properties) { outputBuffer.putShort(Version1); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); }

Target:
private static void putBlobPropertiesToBufferV1(ByteBuffer outputBuffer, BlobProperties properties) { outputBuffer.putShort(VERSION_1); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); }
Source:
public void handle(HttpExchange exchange) throws IOException { StringBuilder body = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(exchange.getRequestBody())) { char[] buffer = new char[256]; int read; while ((read = reader.read(buffer)) != -1) { body.append(buffer, 0, read); } } String[] delayArray = body.toString().split("="); int delay = Integer.parseInt(delayArray[1]); setAnimationDelay(delay); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); os.close(); }

Target:
public void handle(HttpExchange exchange) throws IOException { Headers headers = exchange.getResponseHeaders(); headers.add("Content-type", "application/json"); headers.add("Access-Control-Allow-Origin", "*"); String body = ""; String response = ""; if ("POST".equals(exchange.getRequestMethod())) { try (InputStreamReader reader = new InputStreamReader(exchange.getRequestBody())) { body = new BufferedReader(reader).lines().collect(Collectors.joining("\n")); } String[] animationDelayArray = body.split("="); int animationDelay = Integer.parseInt(animationDelayArray[1]); setAnimationDelay(animationDelay); } else { response = "{\"animationDelay\":\"" + diagnosticsPlugin.getAnimationDelay() + "\"}"; } exchange.sendResponseHeaders(200, response.length()); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); }
Source:
void processBatch(Collection<Metric> metrics) throws InterruptedException { OpenTsdbClient client = null; boolean flushed = false; try { long processed = 0; client = getOpenTsdbClient(); if (client != null) { int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } if ( clientPool.hasCollision()) { eventBus.post(Control.highCollision()); throw new NoSuchElementException("Collision detected"); } try { for (Metric m : metrics) { final String clientId = m.removeTag(TsdbMetricsQueue.CLIENT_TAG); try { final String message = convert(m); client.put(message); processed++; } catch (Exception e) { log.warn("Caught (and rethrowing) exception while processing metric: {}", e.getMessage()); throw e; } finally { m.addTag(TsdbMetricsQueue.CLIENT_TAG, clientId); } } client.flush(); flushed = true; metricsQueue.incrementProcessed(processed); } catch (IOException e) { log.warn("Caught exception while processing messages: {}", e.getMessage()); if (null != client) { client.close(); } } } else { log.warn("Unable to get client to process metrics."); } } finally { if (!flushed) { try { metricsQueue.reAddAll(metrics); } catch (Exception e) { log.error("We were unable to add metrics back to the queue. Eating exception to prevent thread death.", e); } } if (client != null) { try { clientPool.returnObject(client); } catch (Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } lastWorkTime = System.currentTimeMillis(); } }

Target:
void processBatch(Collection<Metric> metrics) throws InterruptedException { OpenTsdbClient client = null; boolean flushed = false; try { long processed = 0; client = getOpenTsdbClient(); if (client != null) { int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } if ( clientPool.hasCollision()) { eventBus.post(Control.highCollision()); throw new NoSuchElementException("Collision detected"); } try { for (Metric m : metrics) { Metric workingCopy = new Metric(m); workingCopy.removeTag(TsdbMetricsQueue.CLIENT_TAG); try { final String message = convert(workingCopy); client.put(message); processed++; } catch (IOException e) { log.warn("Caught (and rethrowing) IOException while processing metric: {}", e.getMessage()); throw e; } } client.flush(); flushed = true; metricsQueue.incrementProcessed(processed); } catch (IOException e) { log.warn("Caught exception while processing messages: {}", e.getMessage()); if (null != client) { client.close(); } } } else { log.warn("Unable to get client to process metrics."); } } finally { if (!flushed) { try { metricsQueue.reAddAll(metrics); } catch (IllegalStateException e) { log.error("We were unable to add metrics back to the queue. Eating exception to prevent thread death.", e); } } if (client != null) { try { clientPool.returnObject(client); } catch (Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } lastWorkTime = System.currentTimeMillis(); } }
Source:
private static <T> BiFunction<Set<T>, Set<T>, Set<T>> mergeSetsAccountingForSingletons() { return (newValue, oldValue) -> { if (oldValue.size() == 1) { Set<T> newMutableSet = new HashSet<>(); newMutableSet.addAll(oldValue); newMutableSet.addAll(newValue); return newMutableSet; } else { oldValue.addAll(newValue); return oldValue; } }; }

Target:
private static <T> BiFunction<Set<T>, Set<T>, Set<T>> mergeSetsAccountingForSingletons() { return (newValue, oldValue) -> { final Set<T> mutableSet = oldValue.size() == 1 ? new HashSet<>() : oldValue; mutableSet.addAll(oldValue); mutableSet.addAll(newValue); return mutableSet; }; }
Source:
private List<JavaFileScannerContext.Location> learnedConstraintFlow(LearnedConstraint learnedConstraint, ExplodedGraph.Edge edge) { Constraint constraint = learnedConstraint.constraint(); if (constraint == null || !addToFlow.test(constraint)) { return ImmutableList.of(); } ExplodedGraph.Node parent = edge.parent; Tree nodeTree = parent.programPoint.syntaxTree(); if (isMethodInvocationNode(parent)) { return methodInvocationFlow(constraint, edge); } if (nodeTree.is(Tree.Kind.NEW_CLASS)) { return ImmutableList.of(location(parent, String.format("Constructor implies '%s'.", constraint.valueAsString()))); } String msg; Tree reportTree = parent.programPoint.syntaxTree(); Symbol finalField = learnedConstraintOnFinalField(reportTree); if (finalField != null) { msg = String.format(IMPLIES_IS_MSG, finalField.name(), constraint.valueAsString()); reportTree = ((VariableTree) finalField.declaration()).initializer(); } else { String name = SyntaxTreeNameFinder.getName(nodeTree); if (name == null) { return ImmutableList.of(); } if (ObjectConstraint.NULL == constraint && isNullCheck(nodeTree)) { msg = String.format(IMPLIES_CAN_BE_NULL_MSG, name); } else { msg = String.format(IMPLIES_IS_MSG, name, constraint.valueAsString()); } } return ImmutableList.of(new JavaFileScannerContext.Location(msg, reportTree)); }

Target:
private List<JavaFileScannerContext.Location> learnedConstraintFlow(LearnedConstraint learnedConstraint, ExplodedGraph.Edge edge) { Constraint constraint = learnedConstraint.constraint(); if (constraint == null || !addToFlow.test(constraint)) { return ImmutableList.of(); } ExplodedGraph.Node parent = edge.parent; Tree nodeTree = parent.programPoint.syntaxTree(); if (isMethodInvocationNode(parent)) { return methodInvocationFlow(constraint, edge); } if (nodeTree.is(Tree.Kind.NEW_CLASS)) { return ImmutableList.of(location(parent, String.format("Constructor implies '%s'.", constraint.valueAsString()))); } Symbol finalField = learnedConstraintOnFinalField(nodeTree); if (finalField != null) { String msg = String.format(IMPLIES_IS_MSG, finalField.name(), constraint.valueAsString()); return ImmutableList.of(new JavaFileScannerContext.Location(msg, ((VariableTree) finalField.declaration()).initializer())); } String name = SyntaxTreeNameFinder.getName(nodeTree); if (name == null) { return ImmutableList.of(); } String msg; if (ObjectConstraint.NULL == constraint && isNullCheck(nodeTree)) { msg = String.format(IMPLIES_CAN_BE_NULL_MSG, name); } else { msg = String.format(IMPLIES_IS_MSG, name, constraint.valueAsString()); } return ImmutableList.of(location(parent, msg)); }
Source:
@Test public void runWebTests() throws Exception { List<String> tests = new ArrayList<>(); ATDRunner parallelThread = new ATDRunner(); tests.add("LoginFailureTest"); boolean hasFailures = parallelThread.runner("com.appium.webtest",tests); }

Target:
@Test public void runWebTests() throws Exception { List<String> tests = new ArrayList<>(); ATDRunner atdRunner = new ATDRunner(); tests.add("LoginFailureTest"); boolean hasFailures = atdRunner.runner("com.appium.webtest",tests); }
Source:
public String toString() { return "CallStackEvent start=" + fTime + " end=" + (fTime + fDuration) + " duration=" + fDuration + " value=" + fValue; }

Target:
public String toString() { return getClass().getSimpleName() + " start=" + fTime + " end=" + (fTime + fDuration) + " duration=" + fDuration + " value=" + fValue; }
Source:
public void testCanContribute() { assertTrue(processor.canContribute(mock(IStatus.class))); }

Target:
public void testCanContribute() { assertThat(processor.canContribute(mock(IStatus.class)),is(true)); }
Source:
protected BatchWriter getHistoryWriterFromElementType(Element element) { if (element instanceof Vertex) { return getHistoryVerticesWriter(); } else if (element instanceof Edge) { return getHistoryEdgesWriter(); } else { throw new VertexiumException("Unexpected element type: " + element.getClass().getName()); } }

Target:
public BatchWriter getHistoryWriterFromElementType(Element element) { return getHistoryWriterFromElementType(ElementType.getTypeFromElement(element)); }
Source:
public void testMergeEmptyBranches() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("initial commit").call(); RefUpdate r = db.updateRef("refs/heads/side"); r.setNewObjectId(db.resolve(Constants.HEAD)); assertEquals(r.forceUpdate(), RefUpdate.Result.NEW); git.commit().setMessage("second commit").setCommitter(committer).call(); db.updateRef(Constants.HEAD).link("refs/heads/side"); git.commit().setMessage("first side commit").setAuthor(author).call(); FileWriter wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_HEAD)); wr.write(ObjectId.toString(db.resolve("refs/heads/master"))); wr.close(); wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_MSG)); wr.write("merging"); wr.close(); git.commit().call(); }

Target:
public void testMergeEmptyBranches() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("initial commit").call(); RefUpdate r = db.updateRef("refs/heads/side"); r.setNewObjectId(db.resolve(Constants.HEAD)); assertEquals(r.forceUpdate(), RefUpdate.Result.NEW); RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call(); db.updateRef(Constants.HEAD).link("refs/heads/side"); RevCommit firstSide = git.commit().setMessage("first side commit").setAuthor(author).call(); FileWriter wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_HEAD)); wr.write(ObjectId.toString(db.resolve("refs/heads/master"))); wr.close(); wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_MSG)); wr.write("merging"); wr.close(); RevCommit commit = git.commit().call(); RevCommit[] parents = commit.getParents(); assertEquals(parents[0], firstSide); assertEquals(parents[1], second); assertTrue(parents.length==2); }
Source:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); List<AttributeDescriptor> attributes = metacard .getMetacardType() .getAttributeDescriptors() .stream() .filter(Objects::nonNull) .collect(Collectors.toList()); Appendable appendable = writeMetacardsToCsv(Collections.singletonList(metacard), attributes, aliases); return createResponse(appendable); }

Target:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); Appendable appendable = writeMetacardsToCsv( Collections.singletonList(metacard), new ArrayList<>(metacard.getMetacardType().getAttributeDescriptors()), aliases); return createResponse(appendable); }
Source:
public void whenPromptDoesNotHaveAnswer_buttonShouldLaunchCorrectIntent() { GeoPointWidget widget = createWidget(promptWithAnswer(null)); stubAllRuntimePermissionsGranted(widget, true); widget.startGeoButton.performClick(); Intent startedIntent = shadowOf(widgetTestActivity()).getNextStartedActivity(); Bundle bundle = startedIntent.getExtras(); assertThat(startedIntent.getComponent(), equalTo(new ComponentName(widgetTestActivity(), GeoPointActivity.class))); assertBundleArgumentEquals(bundle, null, DEFAULT_LOCATION_ACCURACY, false, true); }

Target:
public void whenPromptDoesNotHaveAnswer_buttonShouldLaunchCorrectIntent() { GeoPointWidget widget = createWidget(promptWithAnswer(null)); stubLocationPermissions(widget, true); widget.binding.simpleButton.performClick(); Intent startedIntent = shadowOf(widgetTestActivity()).getNextStartedActivity(); Bundle bundle = startedIntent.getExtras(); assertThat(startedIntent.getComponent(), equalTo(new ComponentName(widgetTestActivity(), GeoPointActivity.class))); assertBundleArgumentEquals(bundle, null, DEFAULT_LOCATION_ACCURACY); }
Source:
public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); if (!found[0]) { float scaleFactor = currentDeviceZoom / 100; ImageData resizedData = data.scaledTo((int)(data.width * scaleFactor), (int)(data.height * scaleFactor)); init (resizedData); } else { init (data); } init (); }

Target:
public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); if (found[0]) { init (data); } else { float scaleFactor = currentDeviceZoom / 100; ImageData resizedData = data.scaledTo((int)(data.width * scaleFactor), (int)(data.height * scaleFactor)); init (resizedData); } init (); }