auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void TestTraceBehavior() throws Exception { logger.info("Starting test encoding1={}, encoding2={}, sampled={}", encoding1, encoding2, sampled); String host = tchannel.getListeningHost(); Downstream request = new Downstream( SERVER_NAME, "s3", encoding1, host + ":" + tchannel.getPort(), new Downstream( SERVER_NAME, "s4", encoding2, host + ":" + tchannel.getPort(), null ) ); String baggage = "luggage-" + System.currentTimeMillis(); Span span = tracer.buildSpan("root").startManual(); span.setBaggageItem(BAGGAGE_KEY, baggage); if (sampled) { Tags.SAMPLING_PRIORITY.set(span, 1); } tchannel.getTracingContext().pushSpan(span); Response response = traceBehavior.handleRequest(new Request("s2", request)); logger.info("Response: {}", response); span.finish(); SpanContext spanContext = span.context(); String traceId = String.format("%s", spanContext.toTraceId()); validate(response, traceId, baggage, 2); if (sampled) { for (int i = 0; i < 100; i++) { if (reporter.getSpans().size() == 5) { break; } Thread.sleep(10); } assertEquals(5, reporter.getSpans().size()); } }

Target:
public void TestTraceBehavior() throws Exception { logger.info("Starting test encoding1={}, encoding2={}, sampled={}", encoding1, encoding2, sampled); String host = tchannel.getListeningHost(); Downstream request = new Downstream( SERVER_NAME, "s3", encoding1, host + ":" + tchannel.getPort(), new Downstream( SERVER_NAME, "s4", encoding2, host + ":" + tchannel.getPort(), null ) ); String baggage = "luggage-" + System.currentTimeMillis(); Span span = tracer.buildSpan("root").startManual(); span.setBaggageItem(BAGGAGE_KEY, baggage); if (sampled) { Tags.SAMPLING_PRIORITY.set(span, 1); } tchannel.getTracingContext().pushSpan(span); Response response = traceBehavior.handleRequest(new Request("s2", request)); logger.info("Response: {}", response); span.finish(); String traceId = span.context().toTraceId(); validate(response, traceId, baggage, 2); if (sampled) { for (int i = 0; i < 100; i++) { if (reporter.getSpans().size() == 5) { break; } Thread.sleep(10); } assertEquals(5, reporter.getSpans().size()); } }
Source:
private void bindAndInit(final InteractiveUIContent interactiveUI, CheckboxTableViewer descriptorViewer) { if (isSimple) { interactiveUI.select(defaultSelection); if (defaultCheck != null) { IItemDescriptor<T> defaultCheckedElement = defaultCheck.iterator().next(); interactiveUI.checkElement(defaultCheckedElement); if (dataHolder != null) { dataHolder.setData(Collections.singleton(defaultCheckedElement)); } } descriptorViewer.addCheckStateListener(new SingleCheckListener<T>(dataHolder, descriptorViewer, Display.getDefault().getActiveShell())); } else { interactiveUI.select(defaultSelection); if (defaultCheck != null) { if (dataHolder != null) { dataHolder.setData(defaultCheck); } } if (dataHolder != null) { bindMultipleData(DataHolder.DATA_FIELD_NAME, interactiveUI.getViewer(), dataHolder); } } }

Target:
private void bindAndInit(final InteractiveUIContent interactiveUI, CheckboxTableViewer descriptorViewer) { if (defaultSelection != null) { interactiveUI.select(defaultSelection); } if (isSimple) { if (defaultCheck != null) { IItemDescriptor<T> defaultCheckedElement = defaultCheck.iterator().next(); interactiveUI.checkElement(defaultCheckedElement); if (dataHolder != null) { dataHolder.setData(Collections.singleton(defaultCheckedElement)); } } descriptorViewer.addCheckStateListener(new SingleCheckListener<T>(dataHolder, descriptorViewer, Display.getDefault().getActiveShell())); } else { if (dataHolder != null) { if (defaultCheck != null) { dataHolder.setData(defaultCheck); } bindMultipleData(DataHolder.DATA_FIELD_NAME, interactiveUI.getViewer(), dataHolder); } } }
Source:
public static void extractArchive(File sourceBundle, File root) throws IOException { ZipFile zipfile = new ZipFile(sourceBundle); Enumeration<? extends ZipEntry> e = zipfile.entries(); while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); File file = new File(root, ze.getName()); if (ze.isDirectory()) { file.mkdirs(); } else { try (InputStream in = zipfile.getInputStream(ze); FileOutputStream out = new FileOutputStream(file)) { assertNotNull(in); copyFile(in, out); } } } }

Target:
public static void extractArchive(File sourceBundle, File root) throws IOException { ZipFile zipfile = new ZipFile(sourceBundle); Enumeration<? extends ZipEntry> e = zipfile.entries(); while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); File file = new File(root, ze.getName()); if (ze.isDirectory()) { file.mkdirs(); } else { try (InputStream in = zipfile.getInputStream(ze); FileOutputStream out = new FileOutputStream(file)) { if (in == null) { throw new IOException("Cannot get InputStream for " + ze); } copyFile(in, out); } } } }
Source:
private boolean equalsNetCapabilitiesRequestable(NetworkCapabilities that) { return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) == (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)); }

Target:
private boolean equalsNetCapabilitiesRequestable(NetworkCapabilities that) { return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) == (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)) && ((this.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES) == (that.mUnwantedNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)); }
Source:
public boolean dispatch(Message<?> message) { int dispatched = 0; int sequenceNumber = 1; Collection<MessageHandler> handlers = this.getHandlers(); if (this.requireSubscribers && handlers.size() == 0) { throw new MessageDispatchingException(message, "Dispatcher has no subscribers"); } int sequenceSize = handlers.size(); Message<?> messageToSend = message; UUID sequenceId = null; if (this.applySequence) { sequenceId = message.getHeaders().getId(); } for (MessageHandler handler : handlers) { if (this.applySequence) { if (message instanceof ThreadStatePropagationChannelInterceptor.MessageWithThreadState) { messageToSend = ((ThreadStatePropagationChannelInterceptor.MessageWithThreadState) message) .cloneWithSequenceDetails(sequenceId, sequenceNumber++, sequenceSize); } else { messageToSend = getMessageBuilderFactory() .fromMessage(message) .pushSequenceDetails(sequenceId, sequenceNumber++, sequenceSize) .build(); } } if (this.executor != null) { Runnable task = createMessageHandlingTask(handler, messageToSend); this.executor.execute(task); dispatched++; } else { if (this.invokeHandler(handler, messageToSend)) { dispatched++; } } } if (dispatched == 0 && this.minSubscribers == 0 && logger.isDebugEnabled()) { if (sequenceSize > 0) { logger.debug("No subscribers received message, default behavior is ignore"); } else { logger.debug("No subscribers, default behavior is ignore"); } } return dispatched >= this.minSubscribers; }

Target:
public boolean dispatch(Message<?> message) { int dispatched = 0; int sequenceNumber = 1; Collection<MessageHandler> handlers = this.getHandlers(); if (this.requireSubscribers && handlers.size() == 0) { throw new MessageDispatchingException(message, "Dispatcher has no subscribers"); } int sequenceSize = handlers.size(); Message<?> messageToSend = message; UUID sequenceId = null; if (this.applySequence) { sequenceId = message.getHeaders().getId(); } for (MessageHandler handler : handlers) { if (this.applySequence) { messageToSend = getMessageBuilderFactory() .fromMessage(message) .pushSequenceDetails(sequenceId, sequenceNumber++, sequenceSize) .build(); if (message instanceof MessageDecorator) { messageToSend = ((MessageDecorator) message).decorateMessage(messageToSend); } } if (this.executor != null) { Runnable task = createMessageHandlingTask(handler, messageToSend); this.executor.execute(task); dispatched++; } else { if (this.invokeHandler(handler, messageToSend)) { dispatched++; } } } if (dispatched == 0 && this.minSubscribers == 0 && logger.isDebugEnabled()) { if (sequenceSize > 0) { logger.debug("No subscribers received message, default behavior is ignore"); } else { logger.debug("No subscribers, default behavior is ignore"); } } return dispatched >= this.minSubscribers; }
Source:
protected Constraint serviceLocationSpread(ConstraintFactory factory) { throw new UnsupportedOperationException("ConstraintCollectors.countDistinct should not count null as a distinct value"); }

Target:
protected Constraint serviceLocationSpread(ConstraintFactory factory) { return factory.from(MrService.class) .join(MrProcessAssignment.class, equal(Function.identity(), MrProcessAssignment::getService)) .groupBy((service, processAssignment) -> service, ConstraintCollectors.countDistinct((service, processAssignment) -> processAssignment.getLocation())) .filter((service, distinctLocationCount) -> distinctLocationCount < service.getLocationSpread()) .penalizeLong(MrConstraints.SERVICE_LOCATION_SPREAD, HardSoftLongScore.ONE_HARD, (service, distinctLocationCount) -> service.getLocationSpread() - distinctLocationCount); }
Source:
public void testSendingWhileResumingInvokesEndpointContextMatcher() throws Exception { TestEndpointContextMatcher endpointMatcher = new TestEndpointContextMatcher(3); client.setEndpointContextMatcher(endpointMatcher); LatchDecrementingRawDataChannel channel = serverHelper.givenAnEstablishedSession(client, false); client.forceResumeAllSessions(); RawData outboundMessage = RawData.outbound(new byte[] { 0x01 }, new AddressEndpointContext(serverHelper.serverEndpoint), null, false); CountDownLatch latch = new CountDownLatch(1); channel.setLatch(latch); client.send(outboundMessage); assertThat(endpointMatcher.await(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), is(true)); assertThat(endpointMatcher.getConnectionEndpointContext(2), is(notNullValue())); assertTrue("DTLS client timed out after " + MAX_TIME_TO_WAIT_SECS + " seconds waitng for response!", latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); }

Target:
public void testSendingWhileResumingInvokesEndpointContextMatcher() throws Exception { TestEndpointContextMatcher endpointMatcher = new TestEndpointContextMatcher(3); client.setEndpointContextMatcher(endpointMatcher); LatchDecrementingRawDataChannel channel = serverHelper.givenAnEstablishedSession(client, false); client.forceResumeAllSessions(); RawData outboundMessage = RawData.outbound(new byte[] { 0x01 }, new AddressEndpointContext(serverHelper.serverEndpoint), null, false); CountDownLatch latch = new CountDownLatch(1); channel.setLatch(latch); client.send(outboundMessage); assertThat(endpointMatcher.await(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), is(true)); assertThat(endpointMatcher.getConnectionEndpointContext(2), is(notNullValue())); assertTrue("DTLS client timed out after " + MAX_TIME_TO_WAIT_SECS + " seconds waiting for response!", latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); }
Source:
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } switch (subQueue) { case NONE: case TRANSFER_QUEUE: break; case DEAD_LETTER_QUEUE: entityPath += "/$deadletterqueue"; break; default: logger.warning("Unsupported value of subqueue type {}.", subQueue); } return entityPath; }

Target:
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName, String topicName, String subscriptionName, SubQueue subQueue) { String entityPath; switch (entityType) { case QUEUE: entityPath = queueName; break; case SUBSCRIPTION: if (isNullOrEmpty(subscriptionName)) { throw logger.logExceptionAsError(new IllegalStateException(String.format( "topicName (%s) must have a subscriptionName associated with it.", topicName))); } entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName, subscriptionName); break; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown entity type: " + entityType)); } if (subQueue == null) { return entityPath; } switch (subQueue) { case NONE: break; case TRANSFER_DEAD_LETTER_QUEUE: entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX; break; case DEAD_LETTER_QUEUE: entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX; break; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: " + subQueue)); } return entityPath; }
Source:
protected ExternalDataObject convertToExternalDataObject(Person person) { ExternalDataObject externalDataObject = new ExternalDataObject(sourceIdentifier); String lastName = ""; String firstName = ""; if (person.getName().getFamilyName() != null) { lastName = person.getName().getFamilyName().getValue(); externalDataObject.addMetadata(new MockMetadataValue("person", "familyName", null, null, lastName)); } if (person.getName().getGivenNames() != null) { firstName = person.getName().getGivenNames().getValue(); externalDataObject.addMetadata(new MockMetadataValue("person", "givenName", null, null, firstName)); } externalDataObject.setId(person.getName().getPath()); externalDataObject .addMetadata(new MockMetadataValue("dc", "identifier", "orcid", null, person.getName().getPath())); externalDataObject .addMetadata(new MockMetadataValue("dc", "identifier", "uri", null, orcidUrl + person.getName().getPath())); if (!StringUtils.isBlank(lastName) && !StringUtils.isBlank(firstName)) { externalDataObject.setDisplayValue(lastName + ", " + firstName); externalDataObject.setValue(lastName + ", " + firstName); } else if (StringUtils.isBlank(firstName)) { externalDataObject.setDisplayValue(lastName); externalDataObject.setValue(lastName); } else if (StringUtils.isBlank(lastName)) { externalDataObject.setDisplayValue(firstName); externalDataObject.setValue(firstName); } return externalDataObject; }

Target:
protected ExternalDataObject convertToExternalDataObject(Person person) { ExternalDataObject externalDataObject = new ExternalDataObject(sourceIdentifier); String lastName = ""; String firstName = ""; if (person.getName().getFamilyName() != null) { lastName = person.getName().getFamilyName().getValue(); externalDataObject.addMetadata(new MetadataValueDTO("person", "familyName", null, null, lastName)); } if (person.getName().getGivenNames() != null) { firstName = person.getName().getGivenNames().getValue(); externalDataObject.addMetadata(new MetadataValueDTO("person", "givenName", null, null, firstName)); } externalDataObject.setId(person.getName().getPath()); externalDataObject .addMetadata(new MetadataValueDTO("dc", "identifier", "orcid", null, person.getName().getPath())); externalDataObject .addMetadata(new MetadataValueDTO("dc", "identifier", "uri", null, orcidUrl + person.getName().getPath())); if (!StringUtils.isBlank(lastName) && !StringUtils.isBlank(firstName)) { externalDataObject.setDisplayValue(lastName + ", " + firstName); externalDataObject.setValue(lastName + ", " + firstName); } else if (StringUtils.isBlank(firstName)) { externalDataObject.setDisplayValue(lastName); externalDataObject.setValue(lastName); } else if (StringUtils.isBlank(lastName)) { externalDataObject.setDisplayValue(firstName); externalDataObject.setValue(firstName); } return externalDataObject; }
Source:
public void testMakesTempBackupEntriesUnlimited() { String mapName = randomMapName(); HazelcastInstance instance = instances[0]; putKeys(instance, mapName, 30, 0, 20); setTtl(instance, mapName, 0, 20, 0, TimeUnit.SECONDS); sleepAtLeastMillis(30100); for (int i = 0; i < CLUSTER_SIZE; i++) { assertKeys(instances, mapName, 0, 20); } }

Target:
public void testMakesTempBackupEntriesUnlimited() { String mapName = randomMapName(); HazelcastInstance instance = instances[0]; putKeys(instance, mapName, 15, 0, 20); setTtl(instance, mapName, 0, 20, 0, TimeUnit.SECONDS); sleepAtLeastMillis(15100); for (int i = 0; i < CLUSTER_SIZE; i++) { assertKeys(instances, mapName, 0, 20); } }
Source:
public void setIn(ContentValues values, Iterable<DateTime> value) { if (value != null) { String stringValue = new Reduced<>( new StringBuilder(256), StringBuilder::append, new Alternating<>( new Mapped<>( DateTime::toString, new Mapped<>(dt -> dt.isFloating() ? dt : dt.shiftTimeZone(DateTime.UTC), value)), new ConstantGenerator<>(","))).value().toString(); values.put(mDateTimeListFieldName, stringValue.isEmpty() ? null : stringValue); } else { values.put(mDateTimeListFieldName, (String) null); } }

Target:
public void setIn(ContentValues values, Iterable<DateTime> value) { if (value != null) { String stringValue = TextUtils.join(",", new Mapped<>(dt -> dt.isFloating() ? dt : dt.shiftTimeZone(DateTime.UTC), value)); values.put(mDateTimeListFieldName, stringValue.isEmpty() ? null : stringValue); } else { values.put(mDateTimeListFieldName, (String) null); } }
Source:
public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.newInvalid(); } if (c <= 127) { len = 0; } else if (c >= 194 && c <= 223) { len = 1; } else if (c >= 224 && c <= 239) { len = 2; } else if (c >= 240 && c <= 244) { len = 3; } else { return Result.newInvalid(); } for (i++; len > 0 && i < buffer.length; i++) { c = buffer[i]; onlyAscii = false; if ((c & 0b11000000) != 0b10000000) { return Result.newInvalid(); } len--; } } return onlyAscii ? new Result(Valid.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); }

Target:
public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.INVALID; } if ((c & 0b10000000) == 0) { len = 0; } else if (c >= 194 && c < 224) { len = 1; } else if ((c & 0b11110000) == 0b11100000) { len = 2; } else if ((c & 0b11111000) == 0b11110000) { len = 3; } else { return Result.INVALID; } while (len > 0) { i++; if (i >= buffer.length) { break; } c = (0xFF) & buffer[i]; onlyAscii = false; if ((c & 0b11000000) != 0b10000000) { return Result.INVALID; } len--; } } return onlyAscii ? new Result(Validation.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); }
Source:
public void getCpuSpeed() { Assume.assumeTrue(SystemUtils.IS_OS_LINUX); final NodeInfo nodeInfo = Mockito.mock(NodeInfo.class); KVMHostInfo.getCpuSpeed(nodeInfo); }

Target:
public void getCpuSpeed() { Assume.assumeTrue(SystemUtils.IS_OS_LINUX); NodeInfo nodeInfo = Mockito.mock(NodeInfo.class); nodeInfo.mhz = 1000; Assert.assertThat(KVMHostInfo.getCpuSpeed(nodeInfo), Matchers.greaterThan(0l)); }
Source:
private void buildHtmlPath(final OperationWithInput<String> continuation) { ProfileOperationRequest request = ProfileOperationRequest .create(getPath()); server_.openProfile(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } continuation.execute(response.getHtmlFile()); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Open Profile", error.getMessage()); continuation.execute(null); } }); }

Target:
private void buildHtmlPath(final OperationWithInput<String> continuation) { ProfileOperationRequest request = ProfileOperationRequest .create(getPath()); server_.openProfile(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } continuation.execute(response.getHtmlFile()); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Open Profile", error.getMessage()); } }); }
Source:
public static RequestHeader parse(ByteBuffer buffer) { short apiKey = -1; try { apiKey = buffer.getShort(); short apiVersion = buffer.getShort(); short headerVersion = ApiKeys.forId(apiKey).headerVersion(apiVersion); buffer.rewind(); return new RequestHeader(new RequestHeaderData( new ByteBufferAccessor(buffer), headerVersion), headerVersion); } catch (UnsupportedVersionException e) { throw new InvalidRequestException("Unknown API key " + apiKey); } catch (Throwable ex) { throw new InvalidRequestException("Error parsing request header. Our best guess of the apiKey is: " + apiKey, ex); } }

Target:
public static RequestHeader parse(ByteBuffer buffer) { short apiKey = -1; try { apiKey = buffer.getShort(); short apiVersion = buffer.getShort(); short headerVersion = ApiKeys.forId(apiKey).headerVersion(apiVersion); buffer.rewind(); return new RequestHeader(new RequestHeaderData( new ByteBufferAccessor(buffer), headerVersion), headerVersion); } catch (UnsupportedVersionException e) { throw new InvalidRequestException("Unknown API key " + apiKey, e); } catch (Throwable ex) { throw new InvalidRequestException("Error parsing request header. Our best guess of the apiKey is: " + apiKey, ex); } }
Source:
private void readHeader() throws IOException { InputStream is = null; PositionalBufferedStream pbs = null; try { is = ParsingUtils.openInputStream(path); if (hasBlockCompressedExtension(path) || hasBlockCompressedExtension(new URI(path))) { is = new GZIPInputStream(new BufferedInputStream(is)); } pbs = new PositionalBufferedStream(is); final SOURCE source = codec.makeSourceFromStream(pbs); header = codec.readHeader(source); } catch (Exception e) { throw new TribbleException.MalformedFeatureFile("Unable to parse header with error: " + e.getMessage(), path, e); } finally { if (pbs != null) pbs.close(); else if (is != null) is.close(); } }

Target:
private void readHeader() throws IOException { InputStream is = null; PositionalBufferedStream pbs = null; try { is = ParsingUtils.openInputStream(path); if (hasBlockCompressedExtension(new URI(URLEncoder.encode(path, "UTF-8")))) { is = new GZIPInputStream(new BufferedInputStream(is)); } pbs = new PositionalBufferedStream(is); final SOURCE source = codec.makeSourceFromStream(pbs); header = codec.readHeader(source); } catch (Exception e) { throw new TribbleException.MalformedFeatureFile("Unable to parse header with error: " + e.getMessage(), path, e); } finally { if (pbs != null) pbs.close(); else if (is != null) is.close(); } }
Source:
public void beforeEach(final ExtensionContext context) { collectParentTestInstances(context) .stream() .flatMap(this::findRestartedContainers) .forEach(adapter -> context.getStore(NAMESPACE) .getOrComputeIfAbsent(adapter.key, k -> adapter.start())); }

Target:
public void beforeEach(final ExtensionContext context) { collectParentTestInstances(context) .parallelStream() .flatMap(this::findRestartContainers) .forEach(adapter -> context.getStore(NAMESPACE) .getOrComputeIfAbsent(adapter.key, k -> adapter.start())); }
Source:
public List<RawUsageRecord> getUsageForSubscription(final UUID subscriptionId, final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { final List<RawUsageRecord> result = new LinkedList<>(); for (final LocalDate curDate : usageData.keySet()) { if (curDate.compareTo(startDate) >= 0 && curDate.compareTo(endDate) < 0) { final List<RawUsageRecord> rawUsageRecords = usageData.get(curDate); if (rawUsageRecords != null && !rawUsageRecords.isEmpty()) { for (RawUsageRecord record : rawUsageRecords) { if (subscriptionId.equals(record.getSubscriptionId())) { result.add(record); } } } } } return result; }

Target:
public List<RawUsageRecord> getUsageForSubscription(final UUID subscriptionId, final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { final List<RawUsageRecord> result = new ArrayList<>(); final List<RawUsageRecord> usageForAccount = getUsageForAccount(startDate, endDate, tenantContext); for (final RawUsageRecord cur : usageForAccount) { if (cur.getSubscriptionId().equals(subscriptionId)) { result.add(cur); } } return result; }
Source:
private static MultiDensityImage generateImageUrlBasedOnCategory(InsightCard.Category category) { final String image1x = String.format(S3_BUCKET_PATH + "%s.png", category.name().toLowerCase()); final String image2x = String.format(S3_BUCKET_PATH + "%s@2x.png", category.name().toLowerCase()); final String image3x = String.format(S3_BUCKET_PATH + "%s@3x.png", category.name().toLowerCase()); return new MultiDensityImage(Optional.fromNullable(image1x), Optional.fromNullable(image2x), Optional.fromNullable(image3x)); }

Target:
private static MultiDensityImage generateImageUrlBasedOnCategory(InsightCard.Category category) { final String categoryName = category.name().toLowerCase(); final String image1x = String.format(S3_BUCKET_PATH + "%s.png", categoryName); final String image2x = String.format(S3_BUCKET_PATH + "%s@2x.png", categoryName); final String image3x = String.format(S3_BUCKET_PATH + "%s@3x.png", categoryName); return new MultiDensityImage(Optional.fromNullable(image1x), Optional.fromNullable(image2x), Optional.fromNullable(image3x)); }
Source:
public void execute(JobExecutionContext jobContext) throws JobExecutionException { Permissionable permissionable; JobDataMap map = jobContext.getJobDetail().getJobDataMap(); String permissionableId = (String) map.get("permissionableId"); String roleId = (String) map.get("roleId"); try { permissionable = (Permissionable) retrievePermissionable(permissionableId); Role role = (Role) roleAPI.loadRoleById(roleId); permissionAPI.cascadePermissionUnder(permissionable, role); permissionAPI.clearCache(); } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } catch (DotSecurityException e) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } }

Target:
public void execute(JobExecutionContext jobContext) throws JobExecutionException { Permissionable permissionable; final JobDataMap map = jobContext.getJobDetail().getJobDataMap(); final String permissionableId = (String) map.get("permissionableId"); final String roleId = (String) map.get("roleId"); final String userId = (String) map.get("userId"); try { permissionable = retrievePermissionable(permissionableId); final Role role = roleAPI.loadRoleById(roleId); permissionAPI.cascadePermissionUnder(permissionable, role); permissionAPI.removePermissionableFromCache(permissionable.getPermissionId()); if (UtilMethods.isSet(userId)){ notificationAPI.generateNotification( new I18NMessage("notification.identifier.cascadepermissionsjob.info.title"), new I18NMessage("notification.cascade.permissions.success"), null, NotificationLevel.INFO, NotificationType.GENERIC, Visibility.USER, userId, userId, userAPI.getSystemUser().getLocale() ); } } catch (DotDataException | DotSecurityException e) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); if (UtilMethods.isSet(userId)){ try { notificationAPI.generateNotification( new I18NMessage("notification.identifier.cascadepermissionsjob.info.title"), new I18NMessage("notification.cascade.permissions.error"), null, NotificationLevel.ERROR, NotificationType.GENERIC, Visibility.USER, userId, userId, userAPI.getSystemUser().getLocale() ); } catch (DotDataException e1) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); } } throw new DotRuntimeException(e.getMessage(), e); } }
Source:
public String stemWord(String word) { word = convertCyrrilicToLatinString(word); if (stopset.contains(word.toLowerCase(new Locale("sr")))) return word; String stemmed = transform(word); for (int i = 0; i < wordPatterns.size(); i++) { Matcher matcher = wordPatterns.get(i).matcher(stemmed); if (matcher.matches()) { if (hasAVowel(matcher.group(1)) && matcher.group(1).length() > 1) return matcher.group(1); } } return stemmed; }

Target:
public String stemWord(String word) { word = convertCyrrilicToLatinString(word); if (stopset.contains(word.toLowerCase(srLocale))) return word; String stemmed = transform(word); for (int i = 0; i < wordPatterns.size(); i++) { Matcher matcher = wordPatterns.get(i).matcher(stemmed); if (matcher.matches()) { if (hasAVowel(matcher.group(1)) && matcher.group(1).length() > 1) return matcher.group(1); } } return stemmed; }
Source:
public void execute(DelegateExecution execution) { Connector connector; IntegrationContext context; String implementation = ((ServiceTask) execution.getCurrentFlowElement()).getImplementation(); String connectorId = StringUtils.substringBefore(implementation, "."); String actionId = StringUtils.substringAfter(implementation, "."); boolean hasMatchingConnectorDefinitions = false; ActionDefinition actionDefinition = null; List<ConnectorDefinition> resultingConnectors = connectorDefinitions.stream().filter(c -> c.getId().equals(connectorId)).collect(Collectors.toList()); if (resultingConnectors == null || resultingConnectors.size() == 0) { context = integrationContextBuilder.from(execution, null); connector = applicationContext.getBean(implementation, Connector.class); } else { hasMatchingConnectorDefinitions = true; if (resultingConnectors.size() != 1) { throw new RuntimeException("Mismatch connector id mapping: " + connectorId); } ConnectorDefinition connectorDefinition = resultingConnectors.get(0); actionDefinition = connectorDefinition.getActions().get(actionId); if (actionDefinition == null) { throw new RuntimeException("Mismatch action id mapping: " + actionId); } context = integrationContextBuilder.from(execution, actionDefinition); connector = applicationContext.getBean(actionDefinition.getName(), Connector.class); } IntegrationContext results = connector.execute(context); Map<String, Object> outBoundVariables = new HashMap<>(); if (!hasMatchingConnectorDefinitions) { outBoundVariables = results.getOutBoundVariables(); } else { for (VariableDefinition variableDefinition : actionDefinition.getOutput()) { Object outBoundVariableValue = results.getOutBoundVariables().get(variableDefinition.getName()); if (outBoundVariableValue != null) { outBoundVariables.put(variableDefinition.getName(), outBoundVariableValue); } } } execution.setVariables(outBoundVariables); leave(execution); }

Target:
public void execute(DelegateExecution execution) { Connector connector; IntegrationContext context; String implementation = ((ServiceTask) execution.getCurrentFlowElement()).getImplementation(); Optional<ActionDefinition> actionDefinitionOptional = connectorActionDefinitionFinder.find(implementation, connectorDefinitions); ActionDefinition actionDefinition = null; if (actionDefinitionOptional.isPresent()) { actionDefinition = actionDefinitionOptional.get(); context = integrationContextBuilder.from(execution, actionDefinition); connector = applicationContext.getBean(actionDefinition.getName(), Connector.class); } else { context = integrationContextBuilder.from(execution, null); connector = applicationContext.getBean(implementation, Connector.class); } IntegrationContext results = connector.execute(context); List<VariableDefinition> outBoundVariableDefinitions = actionDefinition == null ? null : actionDefinition.getOutput(); execution.setVariables(variablesMatchHelper.match(results.getOutBoundVariables(), outBoundVariableDefinitions)); leave(execution); }
Source:
private void retrieveModules() throws IOException { if (sourceType.getValue() == SourceType.MODULE_SELECTION) { ClassLoader classLoader = this.getClass().getClassLoader(); RuntimeInfo runtimeInfo = SalesforceDefinition .getCommonRuntimeInfo("org.talend.components.salesforce.runtime.dataprep.SalesforceDataprepSource"); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, classLoader)) { SalesforceRuntimeSourceOrSink runtime = (SalesforceRuntimeSourceOrSink) sandboxedInstance.getInstance(); SalesforceInputProperties properties = new SalesforceInputProperties("model"); properties.setDatasetProperties(this); runtime.initialize(null, properties); runtime.validate(null); List<NamedThing> moduleNames = runtime.getSchemaNames(null); moduleName.setPossibleNamedThingValues(moduleNames); } } }

Target:
private void retrieveModules() throws IOException { if (sourceType.getValue() == SourceType.MODULE_SELECTION) { Consumer consumer = new Consumer() { @Override public void accept(SalesforceRuntimeSourceOrSink runtime) throws IOException { List<NamedThing> moduleNames = runtime.getSchemaNames(null); moduleName.setPossibleNamedThingValues(moduleNames); } }; runtimeTask(consumer); } }
Source:
public static URL generateTempUrl(SwiftClientCfg cfg, String container, String object, String tempKey, int urlExpirationInterval) { int currentTime = (int) (System.currentTimeMillis() / 1000L); int expirationSeconds = currentTime + urlExpirationInterval; try { URL endpoint = new URL(cfg.getEndPoint()); String method = "GET"; String path = String.format("/v1/AUTH_%s/%s/%s", cfg.getAccount(), container, object); String hmacBody = String.format("%s\n%d\n%s", method, expirationSeconds, path); String signature = calculateRFC2104HMAC(hmacBody, tempKey); path += String.format("?temp_url_sig=%s&temp_url_expires=%d", signature, expirationSeconds); URL tempUrl = new URL(endpoint.getProtocol(), endpoint.getHost(), endpoint.getPort(), path); return tempUrl; } catch (Exception e) { logger.error("Unable to generate temperoary URL " + e.getMessage()); } return null; }

Target:
public static URL generateTempUrl(SwiftClientCfg cfg, String container, String object, String tempKey, int urlExpirationInterval) { int currentTime = (int) (System.currentTimeMillis() / 1000L); int expirationSeconds = currentTime + urlExpirationInterval; try { URL endpoint = new URL(cfg.getEndPoint()); String method = "GET"; String path = String.format("/v1/AUTH_%s/%s/%s", cfg.getAccount(), container, object); String hmacBody = String.format("%s\n%d\n%s", method, expirationSeconds, path); String signature = calculateRFC2104HMAC(hmacBody, tempKey); path += String.format("?temp_url_sig=%s&temp_url_expires=%d", signature, expirationSeconds); URL tempUrl = new URL(endpoint.getProtocol(), endpoint.getHost(), endpoint.getPort(), path); return tempUrl; } catch (Exception e) { logger.error(e.getMessage()); throw new CloudRuntimeException(e.getMessage()); } }
Source:
private void setConstraintConfig(List<List<String>> constraints, Map<String, Integer> spreads, Map<String, Object> config) { if (consolidatedConfigFlag) { Map<String, Map<String,Object>> modifiedConstraints = new HashMap<>(); for (List<String> constraint: constraints) { if (constraint.size() < 2) { continue; } String comp = constraint.get(0); List<String> others = constraint.subList(1, constraint.size()); List<Object> incompatibleComponents = (List<Object>)modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<String,Object>()) .computeIfAbsent(ConstraintSolverStrategy.CONSTRAINT_TYPE_INCOMPATIBLE_COMPONENTS, k -> new ArrayList<Object>()); incompatibleComponents.addAll(others); } for (String comp: spreads.keySet()) { modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<String,Object>()).put(ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, ""+spreads.get(comp)); } config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, modifiedConstraints); } else { config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, constraints); config.put(Config.TOPOLOGY_SPREAD_COMPONENTS, spreads.entrySet().stream().map(e -> Arrays.asList())); } }

Target:
private void setConstraintConfig(List<List<String>> constraints, Map<String, Integer> spreads, Map<String, Object> config) { if (consolidatedConfigFlag) { Map<String, Map<String,Object>> modifiedConstraints = new HashMap<>(); for (List<String> constraint: constraints) { if (constraint.size() < 2) { continue; } String comp = constraint.get(0); List<String> others = constraint.subList(1, constraint.size()); List<Object> incompatibleComponents = (List<Object>) modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<>()) .computeIfAbsent(ConstraintSolverStrategy.CONSTRAINT_TYPE_INCOMPATIBLE_COMPONENTS, k -> new ArrayList<>()); incompatibleComponents.addAll(others); } for (String comp: spreads.keySet()) { modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<>()).put(ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, "" + spreads.get(comp)); } config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, modifiedConstraints); } else { config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, constraints); for (Map.Entry<String, Integer> e: spreads.entrySet()) { if (e.getValue() > 1) { Assert.fail(String.format("Invalid %s=%d for component=%s, expecting 1 for old-style configuration", ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, e.getValue(), e.getKey())); } } config.put(Config.TOPOLOGY_SPREAD_COMPONENTS, new ArrayList(spreads.keySet())); } }
Source:
public static RuntimeException propagate(Throwable t) { return propagate(t, null); }

Target:
public static RuntimeException propagate(Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } }
Source:
public Iterator<ConfigurationError> configErrors() { return configErrors == null ? Collections.emptyIterator() : configErrors.iterator(); }

Target:
public Iterator<ConfigurationError> configErrors() { return configErrors == null ? Collections.<ConfigurationError>emptyIterator() : configErrors.iterator(); }
Source:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); if(i+1 != vals.size()) output += ", "; else output +="]"; } return output; } else return "null"; }

Target:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); if(i+1 == vals.size()) output += "]"; else output +=", "; } return output; } else return "null"; }
Source:
public Class getRealClass() { return testNGMethod.getRealClass(); }

Target:
public Class<?> getRealClass() { return testNGMethod.getRealClass(); }
Source:
private String getStorageKey(boolean perInstance) { return (perInstance) ? m_category + m_instance : m_category; }

Target:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (m_category != "" ? "." + m_category : ""); }
Source:
public void listNetworkSecurityGroups() { final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup); List<NetworkSecurityGroup> result = nsgApi.list(); assertNotNull(result); assertEquals(result.size(), 1); }

Target:
public void listNetworkSecurityGroups() { final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup); List<NetworkSecurityGroup> result = nsgApi.list(); assertNotNull(result); assertEquals(result.size(), 1); NetworkSecurityGroup original = createGroup(); NetworkSecurityGroup nsg = result.get(0); assertEquals(original.name(), nsg.name()); assertEquals(original.location(), nsg.location()); assertEquals(original.tags(), nsg.tags()); assertEquals(nsg.properties().securityRules().size(), 1); NetworkSecurityRule originalRule = original.properties().securityRules().get(0); NetworkSecurityRule nsgRule = nsg.properties().securityRules().get(0); assertEquals(originalRule.name(), nsgRule.name()); assertTrue(originalRule.properties().equals(nsgRule.properties())); }
Source:
public String rmConnect(@FormParam("username") String username, @FormParam("password") String password) throws KeyException, LoginException, RMException, ActiveObjectCreationException, NodeException { if ((username == null || username.trim().isEmpty()) || (password == null || password.trim().isEmpty())) { throw new LoginException("Empty login/password"); } Session session; if (IAM_IS_USED) { session = sessionStore.createIAMSession(username, password.toCharArray()); } else { session = sessionStore.create(username); } session.connectToRM(new CredData(CredData.parseLogin(username), CredData.parseDomain(username), password)); return session.getSessionId(); }

Target:
public String rmConnect(@FormParam("username") String username, @FormParam("password") String password) throws KeyException, LoginException, RMException, ActiveObjectCreationException, NodeException { if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { throw new LoginException("Empty login/password"); } Session session; if (IAM_IS_USED) { session = sessionStore.createIAMSession(username, password.toCharArray()); } else { session = sessionStore.create(username); } session.connectToRM(new CredData(CredData.parseLogin(username), CredData.parseDomain(username), password)); return session.getSessionId(); }
Source:
public synchronized void deferredCommit() { if (deferredSince != 0 && deferredSince < System.currentTimeMillis() - MAX_DEFERRED_PERIOD) { commitDatabase(); } if (deferredSince == 0) { deferredSince = System.currentTimeMillis(); } if (commitTimerTask != null) { commitTimerTask.cancel(); commitTimerTask = null; } commitTimerTask = new CommitTimerTask(); commitTimer.schedule(commitTimerTask, WRITE_DELAY); }

Target:
public synchronized void deferredCommit() { if (deferredSince != 0 && deferredSince < System.nanoTime() - maxDeferredPeriod) { commitDatabase(); } if (deferredSince == 0) { deferredSince = System.nanoTime(); } if (commitTimerTask != null) { commitTimerTask.cancel(); commitTimerTask = null; } commitTimerTask = new CommitTimerTask(); commitTimer.schedule(commitTimerTask, writeDelay); }
Source:
public void testConcatListNull() { final IValidationResult validationResult = validate("Sequence{}->concat(null)"); assertTrue(validationResult.getMessages().isEmpty()); AstResult ast = validationResult.getAstResult(); Set<IType> types = validationResult.getPossibleTypes(ast.getAst()); String message = "Nothing left after concat:\n Empty Sequence defined in extension\n" + " concat can only be called on collections."; assertEquals(1, types.size()); IType type = types.iterator().next(); assertTrue(type instanceof SequenceType); assertTrue(((SequenceType)type).getCollectionType() instanceof NothingType); assertEquals(message, ((NothingType)((SequenceType)type).getCollectionType()).getMessage()); }

Target:
public void testConcatListNull() { final IValidationResult validationResult = validate("Sequence{}->concat(null)"); assertTrue(validationResult.getMessages().isEmpty()); AstResult ast = validationResult.getAstResult(); Set<IType> types = validationResult.getPossibleTypes(ast.getAst()); String message = "Nothing left after concat:\n Empty Sequence defined in extension\n" + " concat can only be called on collections, but null was used as its argument."; assertEquals(1, types.size()); IType type = types.iterator().next(); assertTrue(type instanceof SequenceType); assertTrue(((SequenceType)type).getCollectionType() instanceof NothingType); assertEquals(message, ((NothingType)((SequenceType)type).getCollectionType()).getMessage()); }
Source:
public void testAttributedLambda() throws Exception { IASTTranslationUnit tu = parseAndCheckBindings(); List<IASTAttribute> attributes = getAttributes(tu); assertEquals(1, attributes.size()); IASTAttribute noReturnAttribute = attributes.get(0); assertInstance(noReturnAttribute.getParent(), IASTFunctionDeclarator.class); }

Target:
public void testAttributedLambda() throws Exception { IASTTranslationUnit tu = parseAndCheckBindings(); checkAttributeRelations(getAttributeSpecifiers(tu), IASTFunctionDeclarator.class); }
Source:
static public String sendHttpPostRequest(String url) { String response = null; try { return HttpUtil.executeUrl("POST", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}",e); } return response; }

Target:
static public String sendHttpPostRequest(String url) { String response = null; try { response = HttpUtil.executeUrl("POST", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}", e); } return response; }
Source:
public final int removeWriteState (Uid objUid, int ft) { int status = NOT_PRESENT; Object[] elements = null; LinkedList list = getList(objUid); synchronized (list) { try { elements = list.toArray(); } catch (Exception ex) { elements = null; } } if (elements == null) { tsLogger.logger.trace("No elements"); return status; } for (int i = 0; i < elements.length; i++) { StoreElement element = (StoreElement) elements[i]; if (element != null) { synchronized (_workList) { synchronized (element) { if (!element.removed && element.objUid.equals(objUid)) { switch (element.typeOfWork) { case AsyncStore.WRITE: if (ft == element.fileType) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } else { if (ft == StateType.OS_ORIGINAL) { if (element.fileType == StateType.OS_SHADOW) { if (element.state != null) _currentCacheSize -= element.state .size(); _removedItems++; element.remove(); status = REMOVED; } } } break; case AsyncStore.COMMIT: if (ft == StateType.OS_ORIGINAL) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } break; default: break; } } } } } } if (cacheIsFull()) { synchronized (_workList) { _workList.notify(); } } return status; }

Target:
public final int removeWriteState (Uid objUid, int ft) { int status = NOT_PRESENT; Object[] elements = null; LinkedList list = getList(objUid); synchronized (list) { try { elements = list.toArray(); } catch (Exception ex) { tsLogger.i18NLogger.warn_could_not_extract_array(ex); elements = null; } } if (elements == null) { tsLogger.logger.trace("No elements"); return status; } for (int i = 0; i < elements.length; i++) { StoreElement element = (StoreElement) elements[i]; if (element != null) { synchronized (_workList) { synchronized (element) { if (!element.removed && element.objUid.equals(objUid)) { switch (element.typeOfWork) { case AsyncStore.WRITE: if (ft == element.fileType) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } else { if (ft == StateType.OS_ORIGINAL) { if (element.fileType == StateType.OS_SHADOW) { if (element.state != null) _currentCacheSize -= element.state .size(); _removedItems++; element.remove(); status = REMOVED; } } } break; case AsyncStore.COMMIT: if (ft == StateType.OS_ORIGINAL) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } break; default: break; } } } } } } if (cacheIsFull()) { synchronized (_workList) { _workList.notify(); } } return status; }
Source:
private double[] getPercentages(FeatureCollection collection, Set[] values) throws IOException { Expression prop = getParameters().get(0); GroupByVisitor groupBy = new GroupByVisitor(Aggregate.COUNT, prop, Arrays.asList(prop), null); collection.accepts(groupBy, null); Object[] result = groupBy.getResult().toArray(); return computePercentages(result, collection.size(), values); }

Target:
private double[] getPercentages(FeatureCollection collection, Set[] values) throws IOException { Expression prop = getParameters().get(0); GroupByVisitor groupBy = new GroupByVisitor(Aggregate.COUNT, prop, Arrays.asList(prop), null); collection.accepts(groupBy, null); Map<List, Integer> result = groupBy.getResult().toMap(); return computePercentages(result, collection.size(), values); }
Source:
public static void reloadInstanceInfo(Callback callback) { currentInstance = null; loadingInstance = true; RequestGenerator rg = new RequestGenerator(); InstanceRefreshHandler handler = new InstanceRefreshHandler(callback); String instanceCode = getSharedPreferences().getString("instance_code", ""); rg.getInstanceInfo(instanceCode, handler); }

Target:
public static void reloadInstanceInfo(Callback callback) { String hardCodedInstanceCode = appInstance.getString(R.string.instance_code); String instanceCode; if (!TextUtils.isEmpty(hardCodedInstanceCode)) { instanceCode = hardCodedInstanceCode; } else if (getSharedPreferences().contains(INSTANCE_CODE)) { String neverUsed = ""; instanceCode = getSharedPreferences().getString(INSTANCE_CODE, neverUsed); } else { Log.e(LOG_TAG, "NOT IMPLEMENTED YET"); return; } reloadInstanceInfo(instanceCode, callback); }