auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response add(User user) { validateParameters(user, "userName"); if (!user.getUserName().contains("@")) { validateParameters(user, "domain.id|name"); } String domain = getDomain(user); AdUser adUser = getEntity(AdUser.class, SearchType.AdUser, getSearchPattern(user.getUserName(), domain)); if (adUser == null) { return Response.status(Status.BAD_REQUEST) .entity("No such user: " + user.getUserName() + " in domain " + domain) .build(); } AddUserParameters newUser = new AddUserParameters(); newUser.setVdcUser(map(adUser)); return performCreation(VdcActionType.AddUser, newUser, new UserIdResolver(adUser.getUserId()), BaseResource.class); }

Target:
public Response add(User user) { validateParameters(user, "userName"); if (!isNameConatinsDomain(user)) { validateParameters(user, "domain.id|name"); } String domain = getDomain(user); AdUser adUser = getEntity(AdUser.class, SearchType.AdUser, getSearchPattern(user.getUserName(), domain)); if (adUser == null) { return Response.status(Status.BAD_REQUEST) .entity("No such user: " + user.getUserName() + " in domain " + domain) .build(); } AddUserParameters newUser = new AddUserParameters(); newUser.setVdcUser(map(adUser)); return performCreation(VdcActionType.AddUser, newUser, new UserIdResolver(adUser.getUserId()), BaseResource.class); }
Source:
public void testRowHighlight() { final GridWidgetDnDProxy highlight = mock(GridWidgetDnDProxy.class); final Bounds bounds = new BaseBounds(GRID_X, GRID_Y, GRID_WIDTH, GRID_HEIGHT); final GridData gridData = new BaseGridData(); gridData.appendRow(uiRow); when(state.getEventColumnHighlight()).thenReturn(highlight); when(state.getActiveGridWidget()).thenReturn(gridWidget); when(state.getOperation()).thenReturn(GridWidgetHandlersOperation.ROW_MOVE_PENDING); when(state.getActiveGridRows()).thenReturn(new ArrayList<GridRow>() {{ add(uiRow); }}); when(rendererHelper.getRenderingInformation()).thenReturn(renderingInformation); when(renderingInformation.getBounds()).thenReturn(bounds); when(renderingInformation.getAllRowHeights()).thenReturn(Collections.singletonList(ROW_HEIGHT)); when(gridWidget.getModel()).thenReturn(gridData); when(gridWidget.getHeader()).thenReturn(gridWidgetHeader); when(gridWidget.getWidth()).thenReturn(GRID_WIDTH); when(uiRow.getHeight()).thenReturn(ROW_HEIGHT); handler.onNodeMouseDown(event); verify(highlight).setWidth(GRID_WIDTH); verify(highlight).setHeight(ROW_HEIGHT); verify(highlight).setX(GRID_X); verify(highlight).setY(GRID_Y + HEADER_HEIGHT); verify(layer).batch(); }

Target:
public void testRowHighlight() { final GridWidgetDnDProxy highlight = mock(GridWidgetDnDProxy.class); final Bounds bounds = new BaseBounds(GRID_X, GRID_Y, GRID_WIDTH, GRID_HEIGHT); final GridData gridData = new BaseGridData(); gridData.appendRow(uiRow); when(state.getEventColumnHighlight()).thenReturn(highlight); when(state.getActiveGridWidget()).thenReturn(gridWidget); when(state.getOperation()).thenReturn(GridWidgetHandlersOperation.ROW_MOVE_PENDING); when(state.getActiveGridRows()).thenReturn(Collections.singletonList(uiRow)); when(rendererHelper.getRenderingInformation()).thenReturn(renderingInformation); when(renderingInformation.getBounds()).thenReturn(bounds); when(renderingInformation.getAllRowHeights()).thenReturn(Collections.singletonList(ROW_HEIGHT)); when(gridWidget.getModel()).thenReturn(gridData); when(gridWidget.getHeader()).thenReturn(gridWidgetHeader); when(gridWidget.getWidth()).thenReturn(GRID_WIDTH); when(uiRow.getHeight()).thenReturn(ROW_HEIGHT); handler.onNodeMouseDown(event); verify(highlight).setWidth(GRID_WIDTH); verify(highlight).setHeight(ROW_HEIGHT); verify(highlight).setX(GRID_X); verify(highlight).setY(GRID_Y + HEADER_HEIGHT); verify(layer).batch(); }
Source:
public Description matchClass(ClassTree tree, VisitorState state) { if (MATCHER.matches(tree, state)) { return buildDescription(tree) .setMessage("Immutable type cannot have both inline @Value.Style and meta-annotation applied") .build(); } return Description.NO_MATCH; }

Target:
public Description matchClass(ClassTree tree, VisitorState state) { if (MATCHER.matches(tree, state)) { return describeMatch(tree); } return Description.NO_MATCH; }
Source:
public Lock getLoadLock(String blockName) { int index = (blockName.hashCode() & 0x7fffffff) % loadLocks.length; return loadLocks[index]; }

Target:
public Lock getLoadLock(String blockName) { if (loadLocks == null) return null; int index = Math.abs(blockName.hashCode() % loadLocks.length); return loadLocks[index]; }
Source:
public Response updateFile(@ApiParam(value = "Full path to a file", required = true) @PathParam("path") String path, InputStream content) throws NotFoundException, ForbiddenException, ServerException { final FileEntry file = projectManager.asFile(path); if (file == null) { throw new NotFoundException("File not found for " + path); } executor.execute(() -> { try { file.updateContent(content); } catch (ForbiddenException e) { LOG.warn(e.getLocalizedMessage()); } catch (ServerException e) { LOG.warn(e.getLocalizedMessage()); } eventService.publish(new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.UPDATED, workspace, file.getProject(), file.getPath().toString(), false)); }); return Response.ok().build(); }

Target:
public Response updateFile(@ApiParam(value = "Full path to a file", required = true) @PathParam("path") String path, InputStream content) throws NotFoundException, ForbiddenException, ServerException { final FileEntry file = projectManager.asFile(path); if (file == null) { throw new NotFoundException("File not found for " + path); } file.updateContent(content); eventService.publish(new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.UPDATED, workspace, file.getProject(), file.getPath().toString(), false)); return Response.ok().build(); }
Source:
public <T> Model<T> getOrNull(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) throws NotExportableException { Model m = models.get(type); if(m==null && type.getAnnotation(ExportedBean.class) != null) { m = new Model<T>(this, type, propertyOwner, property); } return m; }

Target:
public <T> Model<T> getOrNull(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) { Model<T> m = models.get(type); if(m==null && type.getAnnotation(ExportedBean.class) != null) { m = new Model<T>(this, type, propertyOwner, property); } return m; }
Source:
public Object update(String type, String id, ApiRequest request, ResourceManager next) { Service service = objectManager.loadResource(Service.class, id); request = validateLaunchConfigs(service, request); validateSelector(request); validateLbConfig(request, type); validatePorts(service, type, request); RevisionDiffomatic diff = revisionManager.createNewRevision(request.getSchemaFactory(), service, CollectionUtils.toMap(request.getRequestObject())); request.setRequestObject(diff.getNewRevisionData()); Object result = super.update(type, id, request, next); if (result instanceof Service) { service = (Service)result; service = revisionManager.assignRevision(diff, service); processManager.update(service, null); return objectManager.reload(service); } return result; }

Target:
public Object update(String type, String id, ApiRequest request, ResourceManager next) { Service service = objectManager.loadResource(Service.class, id); validateLaunchConfigs(service, request); validateNetworMode(service, request); validateSelector(request); validateLbConfig(request, type); validatePorts(service, type, request); RevisionDiffomatic diff = revisionManager.createNewRevision(request.getSchemaFactory(), service, CollectionUtils.toMap(request.getRequestObject())); request.setRequestObject(diff.getNewRevisionData()); Object result = super.update(type, id, request, next); if (result instanceof Service) { service = (Service)result; service = revisionManager.assignRevision(diff, service); processManager.update(service, null); return objectManager.reload(service); } return result; }
Source:
public static void main(String[] args) { Javalin app = Javalin.create().start(8080); app.get("/plaintext", ctx -> ctx.result("Hello, World!")); app.get("/json", ctx -> { Map<String, String> hello = new HashMap<>(); hello.put("message", "Hello, World!"); ctx.json(hello); }); }

Target:
public static void main(String[] args) { Javalin app = Javalin.create().start(8080); app.get("/plaintext", ctx -> ctx.result("Hello, World!")); app.get("/json", ctx -> { ctx.json(Collections.singletonMap("message", "Hello, World!")); }); }
Source:
public void getCopyAuthorization() { final String resourceId = "target-resource-Id"; final String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource Id; %s, target resource region: %s%n", copyAuthorization.getModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpirationDateTimeTicks(), copyAuthorization.getResourceId(), copyAuthorization.getResourceRegion() )); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorization#string-string }

Target:
public void getCopyAuthorization() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource Id; %s, target resource region: %s%n", copyAuthorization.getModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpiresOn(), copyAuthorization.getResourceId(), copyAuthorization.getResourceRegion() )); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorization#string-string }
Source:
protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { char nullChar = (char) 0; from("ChatScript://localhost:1024/Harry?chatusername=varun&resetchat=true") .setBody (simple ("Hello" )) .log("Body=${body}") .to("ChatScript://localhost:1024/Harry?chatusername=varun") .log("Chat Reponse=${body}") .setBody (simple ("No" )) .to("ChatScript://localhost:1024/Harry?chatusername=varun") .to("mock:result"); } }; }

Target:
protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws JsonProcessingException { String g = "CS" + Math.random(); ChatScriptMessage rqMsg = new ChatScriptMessage(g, "", ""); ChatScriptMessage rq2Msg = new ChatScriptMessage(g, "", "Hello"); ChatScriptMessage rq3Msg = new ChatScriptMessage(g, "", "No"); String rq = ""; String rq2 = ""; String rq3 = ""; try { rq = new ObjectMapper().writeValueAsString(rqMsg); rq2 = new ObjectMapper().writeValueAsString(rq2Msg); rq3 = new ObjectMapper().writeValueAsString(rq3Msg); } catch (JsonProcessingException e) { e.printStackTrace(); } from("timer://foo?repeatCount=1") .setBody(new SimpleExpression(rq)) .to("chatscript://localhost:1024/Harry?resetchat=true") .log("Response 2 = ${body}") .setBody(new SimpleExpression(rq2)) .to("chatscript://localhost:1024/Harry") .log("Response 3 = ${body}") .setBody(new SimpleExpression(rq3)) .to("chatscript://localhost:1024/Harry") .log("Response 4 = ${body}") .to("mock:result"); } }; }
Source:
public static Socket openMonitorSession(final String ip, final int port, final String passwd) throws IOException { Socket sk = new Socket(ip, port); sk.setSoTimeout(45 * 1000); BufferedReader inputStream = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintWriter outputStream = new PrintWriter(sk.getOutputStream(), true); String response = readUntilDelimiter(inputStream); outputStream.write(socketMonitor); outputStream.flush(); response = readUntilDelimiter(inputStream); if (isACK(response) != true) { String nonce = response.substring(2, response.length() - 2); String p = calcPass(passwd, nonce); outputStream.write("*#" + p + "##"); outputStream.flush(); response = readUntilDelimiter(inputStream); if (isACK(response) != true) { throw new IOException(); } } return sk; }

Target:
public static Socket openMonitorSession(final String ip, final int port, final String passwd) throws IOException { Socket sk = new Socket(ip, port); sk.setSoTimeout(45 * 1000); BufferedReader inputStream = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintWriter outputStream = new PrintWriter(sk.getOutputStream(), true); String response = readUntilDelimiter(inputStream); outputStream.write(socketMonitor); outputStream.flush(); response = readUntilDelimiter(inputStream); if (!isACK(response)) { String nonce = response.substring(2, response.length() - 2); String p = calcPass(passwd, nonce); outputStream.write("*#" + p + "##"); outputStream.flush(); response = readUntilDelimiter(inputStream); if (!isACK(response)) { throw new IOException("Invalid gateway password"); } } return sk; }
Source:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof RecordSchema)) return false; RecordSchema that = (RecordSchema) o; if (!equalCachedHash(that)) return false; if (!equalNames(that)) return false; if (!propsEqual(that)) return false; Set seen = SEEN_EQUALS.get(); SeenPair here = new SeenPair(this, o); if (seen.contains(here)) return true; boolean first = seen.isEmpty(); try { seen.add(here); return (fields == null && that.fields == null) || (fields != null && fields.equals(that.fields)); } finally { if (first) seen.clear(); } }

Target:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof RecordSchema)) return false; RecordSchema that = (RecordSchema) o; if (!equalCachedHash(that)) return false; if (!equalNames(that)) return false; if (!propsEqual(that)) return false; Set seen = SEEN_EQUALS.get(); SeenPair here = new SeenPair(this, o); if (seen.contains(here)) return true; boolean first = seen.isEmpty(); try { seen.add(here); return Objects.equals(fields, that.fields); } finally { if (first) seen.clear(); } }
Source:
public void penaltyMatrixDiffOrderTooHighTest() { @SuppressWarnings("unused") DoubleMatrix2D p = getPenaltyMatrix(6, 10); }

Target:
public void penaltyMatrixDiffOrderTooHighTest() { getPenaltyMatrix(6, 10); }
Source:
public void setUp() throws SQLException, IllegalStateException { prepareMariaDB(); createMysqlTable(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); tEnv = StreamTableEnvironment.create(env); createFlinkTable(); prepareData(); }

Target:
public void setUp() throws SQLException, IllegalStateException { createMysqlTable(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); tEnv = StreamTableEnvironment.create(env); createFlinkTable(); prepareData(); }
Source:
public void testTwoBrokerCluster() { final KafkaCluster cluster = app.createAndManageChild(EntitySpec.create(KafkaCluster.class) .configure(KafkaCluster.INITIAL_SIZE, 2)); cluster.start(ImmutableList.of(testLocation)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Callable<Void>() { @Override public Void call() { assertTrue(cluster.getAttribute(Startable.SERVICE_UP)); assertTrue(cluster.getZooKeeper().getAttribute(Startable.SERVICE_UP)); assertEquals(cluster.getCurrentSize().intValue(), 2); return null; } }); Entities.dumpInfo(cluster); KafkaSupport support = new KafkaSupport(cluster); support.sendMessage("brooklyn", "TEST_MESSAGE"); try { Thread.sleep(Duration.seconds(5).toMilliseconds()); String message = support.getMessage("brooklyn"); assertEquals(message, "TEST_MESSAGE"); } catch (InterruptedException e) { e.printStackTrace(); } }

Target:
public void testTwoBrokerCluster() throws InterruptedException { final KafkaCluster cluster = app.createAndManageChild(EntitySpec.create(KafkaCluster.class) .configure(KafkaCluster.INITIAL_SIZE, 2)); cluster.start(ImmutableList.of(testLocation)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Callable<Void>() { @Override public Void call() { assertTrue(cluster.getAttribute(Startable.SERVICE_UP)); assertTrue(cluster.getZooKeeper().getAttribute(Startable.SERVICE_UP)); assertEquals(cluster.getCurrentSize().intValue(), 2); return null; } }); Entities.dumpInfo(cluster); KafkaSupport support = new KafkaSupport(cluster); support.sendMessage("brooklyn", "TEST_MESSAGE"); Thread.sleep(Duration.seconds(5).toMilliseconds()); String message = support.getMessage("brooklyn"); assertEquals(message, "TEST_MESSAGE"); }
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { final byte[] bytes; try { bytes = Java9Support.readFully(input); } catch (final IOException e) { throw instrumentError(name, e); } output.write(instrument(bytes, name)); }

Target:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }
Source:
protected List<FormItem> modifyFormItemsAfterCreation(PluginDescriptor focusedInfrastructurePlugin, PluginDescriptor focusedPolicyPlugin) { List<String> policyDynamicFieldFullNames = focusedPolicyPlugin.getConfigurableFields() .stream() .filter(PluginDescriptor.Field::isDynamic) .map(field -> focusedPolicyPlugin.getPluginName() + field.getName()) .collect(Collectors.toList()); List<String> infrastructureDynamicFieldFullNames = focusedInfrastructurePlugin.getConfigurableFields() .stream() .filter(PluginDescriptor.Field::isDynamic) .map(field -> focusedPolicyPlugin.getPluginName() + field.getName()) .collect(Collectors.toList()); List<String> allDynamicFieldFullNames = new LinkedList<>(); allDynamicFieldFullNames.addAll(policyDynamicFieldFullNames); allDynamicFieldFullNames.addAll(infrastructureDynamicFieldFullNames); List<FormItem> allFormItemsWithHiddenFields = new LinkedList<>(); for (FormItem formItem : this.allFormItems) { allFormItemsWithHiddenFields.add(formItem); if (allDynamicFieldFullNames.stream() .noneMatch(fieldFullName -> isItemEqualToDynamicField(formItem, fieldFullName))) { if (this.allFormItemsPerPlugin.keySet() .stream() .anyMatch(pluginName -> formItem.getName().startsWith(pluginName)) || formItem.getName().equals(INFRASTRUCTURE_FORM_KEY) || formItem.getName().equals(POLICY_FORM_KEY)) { disableNonDynamicItem(allFormItemsWithHiddenFields, formItem); } } } return allFormItemsWithHiddenFields; }

Target:
protected List<FormItem> modifyFormItemsAfterCreation(PluginDescriptor focusedInfrastructurePlugin, PluginDescriptor focusedPolicyPlugin) { List<String> infrastructureDynamicFieldFullNames = focusedInfrastructurePlugin.getConfigurableFields() .stream() .filter(PluginDescriptor.Field::isDynamic) .map(field -> focusedInfrastructurePlugin.getPluginName() + field.getName()) .collect(Collectors.toList()); List<String> policyDynamicFieldFullNames = focusedPolicyPlugin.getConfigurableFields() .stream() .filter(PluginDescriptor.Field::isDynamic) .map(field -> focusedPolicyPlugin.getPluginName() + field.getName()) .collect(Collectors.toList()); List<String> allDynamicFieldFullNames = new LinkedList<>(); allDynamicFieldFullNames.addAll(infrastructureDynamicFieldFullNames); allDynamicFieldFullNames.addAll(policyDynamicFieldFullNames); List<FormItem> allFormItemsWithHiddenFields = new LinkedList<>(); for (FormItem formItem : this.allFormItems) { allFormItemsWithHiddenFields.add(formItem); if (allDynamicFieldFullNames.stream() .noneMatch(fieldFullName -> isItemEqualToDynamicField(formItem, fieldFullName))) { filterAndDisableNonDynamicItem(allFormItemsWithHiddenFields, formItem); } } return allFormItemsWithHiddenFields; }
Source:
public void appendFrom(ReadableByteChannel channel, long size) throws IOException { if (endOffset.get() + size > capacityInBytes) { metrics.overflowWriteError.inc(); throw new IllegalArgumentException( "Channel cannot be written to segment [" + file.getAbsolutePath() + "] because" + " it exceeds the capacity [" + capacityInBytes + "]"); } else { if (!fileChannel.isOpen()) { throw new ClosedChannelException(); } long bytesWritten = 0; long bytesRead = 0; ByteBuffer bytebuffer = ByteBuffer.allocateDirect((int) size); while (bytesRead < size) { bytesRead += channel.read(bytebuffer); } bytebuffer.flip(); while (bytebuffer.hasRemaining()) { bytesWritten += fileChannel.write(bytebuffer, endOffset.get() + bytesWritten); } endOffset.addAndGet(bytesWritten); } }

Target:
public void appendFrom(ReadableByteChannel channel, long size) throws IOException { if (endOffset.get() + size > capacityInBytes) { metrics.overflowWriteError.inc(); throw new IllegalArgumentException( "Channel cannot be written to segment [" + file.getAbsolutePath() + "] because" + " it exceeds the capacity [" + capacityInBytes + "]"); } else { if (!fileChannel.isOpen()) { throw new ClosedChannelException(); } int bytesWritten = 0; while (bytesWritten < size) { byteBufferForAppend.position(0); if (byteBufferForAppend.capacity() > size - bytesWritten) { byteBufferForAppend.limit((int) size - bytesWritten); } else { byteBufferForAppend.limit(byteBufferForAppend.capacity()); } if (channel.read(byteBufferForAppend) < 0) { throw new IOException("ReadableByteChannel length less than requested size!"); } byteBufferForAppend.flip(); while (byteBufferForAppend.hasRemaining()) { bytesWritten += fileChannel.write(byteBufferForAppend, endOffset.get() + bytesWritten); } } endOffset.addAndGet(bytesWritten); } }
Source:
public static String getResizedImageFile(Context context, Uri uri, float multiplier){ File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + "/tempAttachments/"); tempAttachmentsDirectory.mkdirs(); final File tempFile = new File(tempAttachmentsDirectory, String.valueOf(System.currentTimeMillis()) + ".tmp"); Bitmap bitmap = null; Bitmap resized = null; try { bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * multiplier), (int) (bitmap.getHeight() * multiplier), true); FileOutputStream out = new FileOutputStream(tempFile); resized.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); } catch (IOException e) { e.printStackTrace(); return ""; } return tempFile.getAbsolutePath(); }

Target:
public static String getResizedImageFile(Context context, Uri uri, float multiplier) { File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); tempAttachmentsDirectory.mkdirs(); File tempFile = null; Bitmap bitmap = null; Bitmap resized = null; FileOutputStream out = null; try { tempFile = File.createTempFile("TempResizedAttachment", null, tempAttachmentsDirectory); bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * multiplier), (int) (bitmap.getHeight() * multiplier), true); out = new FileOutputStream(tempFile); resized.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (IOException e) { Timber.e(e, "Error while resizing image attachment"); return ""; } finally { IOUtils.closeQuietly(out); } return tempFile.getAbsolutePath(); }
Source:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { List<VDS> vdss = getVdsDao().getAllForStoragePoolAndStatus(getVdsDao().get(vdsId).getStoragePoolId(), VDSStatus.Up); for (VDS vds : vdss) { if (vds.getGlusterVersion() == null) { log.error("Couldn't found glusterfs-server package on vds (needed for creating gluster storage domain).", vds.getName()); StorageHelperBase.addMessageToAuditLog(AuditLogType.GLUSTER_PACKAGES_NOT_INSTALLED, null, vds.getName()); return new Pair<>(false, null); } } return super.runConnectionStorageToDomain(storageDomain, vdsId, type); }

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { VDS vds = getVdsDao().get(vdsId); if (!isGlusterfsCliInstalled(vds)) { log.error("Coulsn't find glusterfs-cli package on vds (needed for connecting storage domain {}).", vds.getName(), storageDomain.getName()); StorageHelperBase.addMessageToAuditLog(AuditLogType.GLUSTERFS_CLI_PACKAGE_NOT_INSTALLED, null, vds.getName()); return new Pair<>(false, null); } return super.runConnectionStorageToDomain(storageDomain, vdsId, type); }
Source:
public View createPatientRow(Patient patient, View convertView, ViewGroup parent, Context context) { ViewHolder holder; if (convertView == null) { LayoutInflater layoutInflater = LayoutInflater.from(context); convertView = layoutInflater.inflate(R.layout.item_patients_list_multi_checkable, parent, false); holder = new ViewHolder(); holder.genderImg = convertView.findViewById(R.id.genderImg); holder.name = convertView.findViewById(R.id.name); holder.dateOfBirth = convertView.findViewById(R.id.dateOfBirth); holder.distanceToHome = convertView.findViewById(R.id.distanceToHome); holder.identifier = convertView.findViewById(R.id.identifier); holder.tagsScroller = convertView.findViewById(R.id.tags_scroller); holder.tagsLayout = convertView.findViewById(R.id.menu_tags); holder.tags = new ArrayList<>(); convertView.setTag(holder); } holder = (ViewHolder) convertView.getTag(); holder.dateOfBirth.setText(String.format("DOB: %s", getFormattedDate(patient.getBirthdate()))); holder.identifier.setText(patient.getIdentifier()); holder.distanceToHome.setText(getDistanceToHome(patient)); holder.name.setText(getPatientFullName(patient)); holder.genderImg.setImageResource(getGenderImage(patient.getGender())); addTags(holder,patient); return convertView; }

Target:
public View createPatientRow(Patient patient, View convertView, ViewGroup parent, Context context) { ViewHolder holder; if (convertView == null) { LayoutInflater layoutInflater = LayoutInflater.from(context); convertView = layoutInflater.inflate(R.layout.item_patients_list_multi_checkable, parent, false); holder = new ViewHolder(); holder.genderImg = convertView.findViewById(R.id.genderImg); holder.name = convertView.findViewById(R.id.name); holder.dateOfBirth = convertView.findViewById(R.id.dateOfBirth); holder.distanceToClientAddress = convertView.findViewById(R.id.distanceToClientAddress); holder.identifier = convertView.findViewById(R.id.identifier); holder.tagsScroller = convertView.findViewById(R.id.tags_scroller); holder.tagsLayout = convertView.findViewById(R.id.menu_tags); holder.tags = new ArrayList<>(); convertView.setTag(holder); } holder = (ViewHolder) convertView.getTag(); holder.dateOfBirth.setText(String.format("DOB: %s", getFormattedDate(patient.getBirthdate()))); holder.identifier.setText(patient.getIdentifier()); holder.distanceToClientAddress.setText(getDistanceToClientAddress(patient)); holder.name.setText(getPatientFullName(patient)); holder.genderImg.setImageResource(getGenderImage(patient.getGender())); addTags(holder,patient); return convertView; }
Source:
public synchronized void executeDetectorIncr(String detector) { executeDetectorCount.scope(detector); }

Target:
public synchronized void executeDetectorIncr(String detector) { executeDetectorCount.scope(detector).incr(); }
Source:
default void log(String msg, DiagnosticEvent event) { FluentLogger.Api severeLogger = logger() .atSevere() .withStackTrace(StackSize.NONE); boolean loggingEnabled = severeLogger.isEnabled(); if (loggingEnabled) { severeLogger.log(msg); severeLogger.log(toJson(event)); } else { @SuppressWarnings("UseOfSystemOutOrSystemErr") PrintStream stderr = System.err; stderr.println(msg); stderr.println(toJson(event)); } }

Target:
default void log(String msg, DiagnosticEvent event) { FluentLogger.Api severeLogger = logger() .atSevere() .withStackTrace(StackSize.NONE); boolean loggingEnabled = severeLogger.isEnabled(); String eventJson = toJson(event); if (loggingEnabled) { severeLogger.log(msg); severeLogger.log(eventJson); } else { @SuppressWarnings("UseOfSystemOutOrSystemErr") PrintStream stderr = System.err; stderr.println(msg); stderr.println(eventJson); } }
Source:
private void updateBookmarkButtons() { if (playlistBookmarkButton == null || activity == null) { return; } final int iconAttr = playlistEntity == null ? R.drawable.ic_playlist_add_white_24dp : R.drawable.ic_playlist_add_check_white_24dp; final int titleRes = playlistEntity == null ? R.string.bookmark_playlist : R.string.unbookmark_playlist; playlistBookmarkButton.setIcon(iconAttr); playlistBookmarkButton.setTitle(titleRes); }

Target:
private void updateBookmarkButtons() { if (playlistBookmarkButton == null || activity == null) { return; } playlistBookmarkButton.setIcon(playlistEntity == null ? R.drawable.ic_playlist_add_white_24dp : R.drawable.ic_playlist_add_check_white_24dp); playlistBookmarkButton.setTitle(playlistEntity == null ? R.string.bookmark_playlist : R.string.unbookmark_playlist); }
Source:
public void validate(Object obj, Errors errors) { RelationshipType relationshipType = (RelationshipType) obj; if (relationshipType == null) { errors.rejectValue("relationshipType", "error.general"); } else { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aIsToB", "RelationshipType.aIsToB.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bIsToA", "RelationshipType.bIsToA.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "Description", "error.description"); } }

Target:
public void validate(Object obj, Errors errors) { RelationshipType relationshipType = (RelationshipType) obj; if (relationshipType == null) { errors.rejectValue("relationshipType", "error.general"); } else { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aIsToB", "RelationshipType.aIsToB.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bIsToA", "RelationshipType.bIsToA.required"); } }
Source:
public void testSerializingUsesISO8601() throws ParseException { Date baseDate = new Date(); Gson gson = new Gson(); String dateString = gson.toJson(baseDate); SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.ISO_8601_DATE_TIME_FORMAT); Date date = formatter.parse(dateString); assertEquals(date, baseDate); }

Target:
public void testSerializingUsesISO8601() throws ParseException { Date baseDate = new Date(); Gson gson = newGson(); String dateString = gson.toJson(baseDate).replace("\"", ""); SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.ISO_8601_DATE_TIME_FORMAT); Date date = formatter.parse(dateString); baseDate = DateUtils.truncate(baseDate, Calendar.SECOND); assertEquals(baseDate.getTime(), date.getTime()); }
Source:
public void setup() { mockSession = mock(Session.class); mockSessionFactory = mock(SessionFactory.class); helper = spy(new HibernateHelper(mockSessionFactory, new AccountPersistentExceptionConverter())); doAnswer(invocation -> { Function<Session, ?> function = invocation.getArgumentAt(0, Function.class); return function.apply(mockSession); }).when(helper).execute(any()); }

Target:
public void setup() { mockSession = mock(Session.class); mockSessionFactory = mock(SessionFactory.class); mockExceptionConverter = mock(PersistenceExceptionConverter.class); helper = spy(new HibernateHelper(mockSessionFactory, mockExceptionConverter)); doAnswer(invocation -> { Function<Session, ?> function = invocation.getArgumentAt(0, Function.class); return function.apply(mockSession); }).when(helper).execute(any()); }
Source:
public CommitStatus setState(final String state) { if (state.equals(STATE_ERROR) || state.equals(STATE_FAILURE) || state.equals(STATE_PENDING) || state.equals(STATE_SUCCESS)) { this.state = state; return this; } throw new IllegalArgumentException(MessageFormat.format("Invalid state {0}", state)); }

Target:
public CommitStatus setState(final String state) { if (STATE_ERROR.equals(state) || STATE_FAILURE.equals(state) || STATE_PENDING.equals(state) || STATE_SUCCESS.equals(state)) { this.state = state; return this; } throw new IllegalArgumentException(MessageFormat.format("Invalid state {0}", state)); }
Source:
public void testAnErrorMessageIsDisplayedWhenAResourceIsUpdatedWithANameAlreadyRegistered() throws InterruptedException { ResourcesPage resourcesPage = new ResourcesPage(); ResourceInfoPage resourceInfoPage = resourcesPage.openResourceInfoPage(resourceUpdateName); resourceInfoPage.setResourceName(resourceName) .setResourceDisplayName(resourceDisplayName) .clickSaveResourceWithErrorBtn(); Assert.assertTrue(RoomBaseAbstractPage.isErrorMessageCorrect(RESOURCE_NAME_DUPLICATED)); resourcesPage = resourceInfoPage.clickCancelResourceBtn(); }

Target:
public void testAnErrorMessageIsDisplayedWhenAResourceIsUpdatedWithANameAlreadyRegistered() throws InterruptedException { ResourcesPage resourcesPage = new ResourcesPage(); ResourceInfoPage resourceInfoPage = resourcesPage.openResourceInfoPage(resourceUpdateName); resourceInfoPage.setResourceName(resourceName) .setResourceDisplayName(resourceDisplayName) .clickSaveResourceWithErrorBtn(); Assert.assertTrue(RoomBaseAbstractPage.isErrorMessageCorrect(RESOURCE_NAME_DUPLICATED)); resourceInfoPage.clickCancelResourceBtn(); }
Source:
public Member getMember(String activityId, String memberId) throws ActivityServiceException { if (StringUtil.isEmpty(activityId)||StringUtil.isEmpty(memberId)){ throw new ActivityServiceException(null, "Null activityId / memberId"); } String requestUri = ActivityServiceUrlBuilder.populateURL(ActivityAction.ACL.getActivityAction()); try { Map<String, String> params = new LinkedHashMap<String, String>(); params.put("activityUuid", activityId); if(EntityUtil.isEmail(memberId)){ params.put("email", memberId); }else{ params.put("memberid", memberId); } return (Member) getEntity(requestUri, params, new MemberFeedHandler(this)); } catch (Exception e) { throw new ActivityServiceException(e); } }

Target:
public Member getMember(String activityId, String memberId) throws ActivityServiceException { if (StringUtil.isEmpty(activityId)||StringUtil.isEmpty(memberId)){ throw new ActivityServiceException(null, "Null activityId / memberId"); } String requestUri = ActivityServiceUrlBuilder.populateURL(ActivityAction.ACL.getActivityAction()); try { Map<String, String> params = new HashMap<String, String>(); params.put("activityUuid", activityId); if(EntityUtil.isEmail(memberId)){ params.put("email", memberId); }else{ params.put("memberid", memberId); } return (Member) getEntity(requestUri, params, new MemberFeedHandler(this)); } catch (Exception e) { throw new ActivityServiceException(e); } }
Source:
public boolean filter(K key, T persistent) { boolean filtered = false; if (operator.equals(Operator.MUST_PASS_ONE)) { for (Filter<K, T> filter: filters) { if (!filter.filter(key, persistent)) { return !filtered; } } } else if (operator.equals(Operator.MUST_PASS_ALL)) { for (Filter<K, T> filter: filters) { if (filter.filter(key, persistent)) { return !filtered; } } } else { throw new IllegalStateException(operator + " not yet implemented!"); } return filtered; }

Target:
public boolean filter(K key, T persistent) { boolean filtered = false; switch (operator.toString()) { case "MUST_PASS_ALL": for (Filter<K, T> filter: filters) { if (!filter.filter(key, persistent)) { return !filtered; } } break; case "MUST_PASS_ONE": for (Filter<K, T> filter: filters) { if (filter.filter(key, persistent)) { return !filtered; } } break; default: throw new IllegalStateException(operator + " not yet implemented!"); } return filtered; }
Source:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeQuotaParam = (String) serverContext.getServerConfig().get("--log-size-quota-percentage"); logSizeLimitPercentage = Double.parseDouble(logSizeQuotaParam); initStreamLogDirectory(); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }

Target:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercentageParam = (String)serverContext.getServerConfig().get("--log-size-quota-percentage"); final double logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercentageParam); if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { String msg = String.format("Invalid quota: quota(%d)% must be between 0-100%", logSizeLimitPercentage); throw new LogUnitException(msg); } long fileSystemCapacity = initStreamLogDirectory(); logSizeLimit = (long)(fileSystemCapacity * logSizeLimitPercentage / 100.0); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }
Source:
public void verifyDecoratorOrder() { DecoratedMacPoolFactory factory = new DecoratedMacPoolFactory(lockedObjectFactorySpy); MacPool decoratedPool = factory.createDecoratedPool(poolId, macPool, Arrays.asList(macPoolDecoratorA, macPoolDecoratorB)); assertThat(decoratedPool, is(macPoolDecoratorB)); assertThat(macPoolDecoratorB.getMacPool(), is(macPoolDecoratorA)); assertThat(macPoolDecoratorA.getMacPool(), is(macPool)); }

Target:
public void verifyDecoratorOrder() { DecoratedMacPoolFactory factory = createDecoratedMacPoolFactoryWithDisabledLocking(); MacPool decoratedPool = factory.createDecoratedPool(poolId, macPool, Arrays.asList(macPoolDecoratorA, macPoolDecoratorB)); assertThat(decoratedPool, is(macPoolDecoratorB)); ArgumentCaptor<MacPool> firstDecoratorMacPoolArgumentCaptor = ArgumentCaptor.forClass(MacPool.class); verify(macPoolDecoratorB).setMacPool(firstDecoratorMacPoolArgumentCaptor.capture()); verify(macPoolDecoratorB).setMacPoolId(any()); assertThat(firstDecoratorMacPoolArgumentCaptor.getValue(), is(macPoolDecoratorA)); ArgumentCaptor<MacPool> secondDecoratorMacPoolArgumentCaptor = ArgumentCaptor.forClass(MacPool.class); verify(macPoolDecoratorA).setMacPool(secondDecoratorMacPoolArgumentCaptor.capture()); verify(macPoolDecoratorA).setMacPoolId(any()); assertThat(secondDecoratorMacPoolArgumentCaptor.getValue(), is(macPool)); Mockito.verifyNoMoreInteractions(macPoolDecoratorA, macPoolDecoratorB, macPool); }
Source:
private void tagCommentLine(String text, int line, int column) { final Matcher offMatcher = offCommentFormat.matcher(text); if (offMatcher.find()) { addTag(offMatcher.group(0), line, column, ReportingOptions.NONE); } else { final Matcher onMatcher = onCommentFormat.matcher(text); if (onMatcher.find()) { addTag(onMatcher.group(0), line, column, ReportingOptions.REPORT); } } }

Target:
private void tagCommentLine(String text, int line, int column) { final Matcher offMatcher = offCommentFormat.matcher(text); if (offMatcher.find()) { addTag(offMatcher.group(0), line, column, TagType.OFF); } else { final Matcher onMatcher = onCommentFormat.matcher(text); if (onMatcher.find()) { addTag(onMatcher.group(0), line, column, TagType.ON); } } }
Source:
public void deleteEntity(Entity entity) { String fieldToRemove = null; String valueToRemove = null; for(String field : docDef.fields()) { if(entity.get(field) != null) { fieldToRemove = field; valueToRemove = (String)entity.get(field); break; } } SearchResponse existsResponse = client.prepareSearch(INDEX_NAME) .setTypes(docDef.getEntityField()) .setQuery(QueryBuilders.existsQuery(fieldToRemove)) .get(); String script = null; if(existsResponse != null && existsResponse.getHits() != null && existsResponse.getHits().totalHits() > 0) { script = "ctx._source." + fieldToRemove+".remove('"+ valueToRemove + "')"; } UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, docDef.getEntityField(), entity.getId()) .script(new Script(script)); try { client.update(updateRequest).get(); }catch(Exception e) { throw new TextIndexException("Unable to delete entity.", e); } LOGGER.debug("deleting content related to entity: " + entity.getId()); }

Target:
public void deleteEntity(Entity entity) { String fieldToRemove = null; String valueToRemove = null; for(String field : docDef.fields()) { if(entity.get(field) != null) { fieldToRemove = field; if(entity.getLanguage()!= null && !entity.getLanguage().isEmpty()) { fieldToRemove = normalizeFieldName(fieldToRemove, entity.getLanguage()); } valueToRemove = (String)entity.get(field); break; } } if(fieldToRemove != null && valueToRemove != null) { LOGGER.debug("deleting content related to entity: " + entity.getId()); String deleteScript = DELETE_SCRIPT.replaceAll("<fieldToRemove>", fieldToRemove); Map<String,Object> params = new HashMap<>(); params.put("valueToRemove", valueToRemove); UpdateRequest updateRequest = new UpdateRequest(indexName, docDef.getEntityField(), entity.getId()) .script(new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG,deleteScript,params)); try { client.update(updateRequest).get(); }catch(Exception e) { if( ExceptionUtils.getRootCause(e) instanceof DocumentMissingException) { LOGGER.debug("Trying to delete values from a missing document. Ignoring deletion of entity: ", entity); } else { throw new TextIndexException("Unable to delete entity.", e); } } } }
Source:
public void handleError(HttpCommand command, HttpResponse response) { String message = errorParser.apply(response); Exception exception = new HttpResponseException(command, response, message); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: exception = new ResourceNotFoundException(message, exception); break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }

Target:
public void handleError(HttpCommand command, HttpResponse response) { String message = errorParser.apply(response); Exception exception = new HttpResponseException(command, response, message); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
private void abandonrestoreButtonEnablement() { Map<String, ActionInfo> actions = fChangeInfo.getActions(); ActionInfo key = actions.get("abandon"); if (key != null && key.isEnabled()) { if (fChangeInfo.getStatus().compareTo("ABANDONED") == 0) { fAbandon.setEnabled(false); fRestore.setEnabled(true); } else { fAbandon.setEnabled(true); fRestore.setEnabled(false); } } else { fAbandon.setEnabled(false); fRestore.setEnabled(false); } }

Target:
private void abandonrestoreButtonEnablement() { Map<String, ActionInfo> actions = fChangeInfo.getActions(); if (actions != null) { ActionInfo abandon = actions.get(ABANDON); ActionInfo restore = actions.get(RESTORE); if (abandon != null && abandon.isEnabled()) { fAbandon.setEnabled(true); fRestore.setEnabled(false); } else if (restore != null && restore.isEnabled()) { fAbandon.setEnabled(false); fRestore.setEnabled(true); } else { fAbandon.setEnabled(false); fRestore.setEnabled(false); } } }
Source:
public void run() { AndroidUtilities.sleepDeep(500L); String groupedQuery; if (query.get().contains("ORDER BY")) groupedQuery = query.get().replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); else groupedQuery = query.get() + " GROUP BY " + Task.ID; Query q = Query.select(Task.ID, Task.TITLE, Task.NOTES, Task.COMPLETION_DATE, new LongProperty(Metadata.TABLE, Metadata.ID.name, METADATA_JOIN + "." + Metadata.ID.name).as(FILE_COLUMN)) .join(Join.left(Metadata.TABLE.as(METADATA_JOIN), Criterion.and(Field.field(METADATA_JOIN + "." + Metadata.KEY.name).eq(FileMetadata.METADATA_KEY), Task.ID.eq(Field.field(METADATA_JOIN + "." + Metadata.TASK.name))))).withQueryTemplate(groupedQuery); final TodorooCursor<Task> fetchCursor = taskService.query(q); try { Task task = new Task(); LinkActionExposer linkActionExposer = new LinkActionExposer(); int filesIndex = fetchCursor.getColumnIndex(FILE_COLUMN); for(fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) { task.clear(); task.readFromCursor(fetchCursor); if(task.isCompleted()) continue; boolean hasAttachments = (filesIndex > 0 && fetchCursor.getLong(filesIndex) > 0); List<TaskAction> actions = linkActionExposer. getActionsForTask(ContextManager.getContext(), task, hasAttachments); if (actions.size() > 0) taskActionLoader.put(task.getId(), actions.get(0)); } } finally { fetchCursor.close(); } final Activity activity = fragment.getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { if(taskActionLoader.size() > 0) { notifyDataSetChanged(); } } }); } }

Target:
public void run() { AndroidUtilities.sleepDeep(500L); String groupedQuery; if (query.get().contains("ORDER BY")) groupedQuery = query.get().replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); else groupedQuery = query.get() + " GROUP BY " + Task.ID; Query q = Query.select(Task.ID, Task.TITLE, Task.NOTES, Task.COMPLETION_DATE, fileIdProperty.as(FILE_COLUMN)) .join(Join.left(Metadata.TABLE.as(METADATA_JOIN), Criterion.and(Field.field(METADATA_JOIN + "." + Metadata.KEY.name).eq(FileMetadata.METADATA_KEY), Task.ID.eq(Field.field(METADATA_JOIN + "." + Metadata.TASK.name))))).withQueryTemplate(groupedQuery); final TodorooCursor<Task> fetchCursor = taskService.query(q); try { Task task = new Task(); LinkActionExposer linkActionExposer = new LinkActionExposer(); for(fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) { task.clear(); task.readFromCursor(fetchCursor); if(task.isCompleted()) continue; boolean hasAttachments = (fetchCursor.get(fileIdProperty) > 0); List<TaskAction> actions = linkActionExposer. getActionsForTask(ContextManager.getContext(), task, hasAttachments); if (actions.size() > 0) taskActionLoader.put(task.getId(), actions.get(0)); } } finally { fetchCursor.close(); } final Activity activity = fragment.getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { if(taskActionLoader.size() > 0) { notifyDataSetChanged(); } } }); } }
Source:
protected void innerDraw(GC gc) { Object lineWidth = fLineWidth; int oldLineWidth = gc.getLineWidth(); Rectangle bounds = getBounds(); gc.setLineWidth((lineWidth instanceof Integer) ? (int) fLineWidth : 1); if (getForegroundColor() != null) { gc.drawRoundRectangle(bounds.x-1, bounds.y-1, bounds.width+2, bounds.height+2, fArc, fArc); } gc.fillRoundRectangle(bounds.x, bounds.y, bounds.width, bounds.height, fArc, fArc); if (fLabel != null && !fLabel.isEmpty() && bounds.width > bounds.height) { gc.setForeground(Utils.getDistinctColor(getBackgroundColor().rgb)); Utils.drawText(gc, fLabel, bounds.x, bounds.y, bounds.width, bounds.height, true, true); } gc.setLineWidth(oldLineWidth); }

Target:
protected void innerDraw(GC gc) { Rectangle bounds = getBounds(); gc.fillRoundRectangle(bounds.x, bounds.y, bounds.width, bounds.height, fArc, fArc); if (fLabel != null && !fLabel.isEmpty() && bounds.width > bounds.height) { gc.setForeground(Utils.getDistinctColor(getBackgroundColor().rgb)); Utils.drawText(gc, fLabel, bounds.x, bounds.y, bounds.width, bounds.height, true, true); } }