auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addBuilder(IBuildConfiguration config, IncrementalProjectBuilder newBuilder) { synchronized (builderLock) { IncrementalProjectBuilder currentBuilder = builders == null ? null : builders.get(config); if (currentBuilder == null && builder == null) { if (supportsConfigs()) { if (builders == null) builders = new HashMap<>(1); builders.put(config, newBuilder); } else builder = newBuilder; } } }

Target:
public void addBuilder(IBuildConfiguration config, IncrementalProjectBuilder newBuilder) { synchronized (builderLock) { IncrementalProjectBuilder configBuilder = builders == null ? null : builders.get(config); if (configBuilder == null && builder == null) { if (supportsConfigs()) { if (builders == null) builders = new HashMap<>(1); builders.put(config, newBuilder); } else builder = newBuilder; } } }
Source:
public void addRanges(String keyspaceName, ReplicaCollection<?> replicas) { Keyspace keyspace = Keyspace.open(keyspaceName); AbstractReplicationStrategy strat = keyspace.getReplicationStrategy(); if(strat instanceof LocalStrategy) { logger.info("Not adding ranges for Local Strategy keyspace={}", keyspaceName); return; } boolean useStrictSource = useStrictSourcesForRanges(strat); EndpointsByReplica fetchMap = calculateRangesToFetchWithPreferredEndpoints(replicas, keyspace, useStrictSource); for (Map.Entry<Replica, Replica> entry : fetchMap.flattenEntries()) logger.info("{}: range exists on for keyspace {}", description, entry.getKey(), entry.getValue(), keyspaceName); Multimap<InetAddressAndPort, FetchReplica> workMap; if (useStrictSource || strat == null || strat.getReplicationFactor().allReplicas == 1 || strat.getReplicationFactor().hasTransientReplicas()) { workMap = convertPreferredEndpointsToWorkMap(fetchMap); } else { workMap = getOptimizedWorkMap(fetchMap, sourceFilters, keyspaceName); } assert toFetch.put(keyspaceName, workMap) == null : "Keyspace is already added to fetch map"; if (logger.isTraceEnabled()) { for (Map.Entry<InetAddressAndPort, Collection<FetchReplica>> entry : workMap.asMap().entrySet()) { for (FetchReplica r : entry.getValue()) logger.trace("{}: range source local range for keyspace {}", description, r.remote, r.local, keyspaceName); } } }

Target:
public void addRanges(String keyspaceName, ReplicaCollection<?> replicas) { Keyspace keyspace = Keyspace.open(keyspaceName); AbstractReplicationStrategy strat = keyspace.getReplicationStrategy(); if(strat instanceof LocalStrategy) { logger.info("Not adding ranges for Local Strategy keyspace={}", keyspaceName); return; } boolean useStrictSource = useStrictSourcesForRanges(strat); EndpointsByReplica fetchMap = calculateRangesToFetchWithPreferredEndpoints(replicas, keyspace, useStrictSource); for (Map.Entry<Replica, Replica> entry : fetchMap.flattenEntries()) logger.info("{}: range exists on for keyspace {}", description, entry.getKey(), entry.getValue(), keyspaceName); Multimap<InetAddressAndPort, FetchReplica> workMap; if (useStrictSource || strat == null || strat.getReplicationFactor().allReplicas == 1 || strat.getReplicationFactor().hasTransientReplicas()) { workMap = convertPreferredEndpointsToWorkMap(fetchMap); } else { workMap = getOptimizedWorkMap(fetchMap, sourceFilters, keyspaceName); } if (toFetch.put(keyspaceName, workMap) != null) throw new IllegalArgumentException("Keyspace is already added to fetch map"); if (logger.isTraceEnabled()) { for (Map.Entry<InetAddressAndPort, Collection<FetchReplica>> entry : workMap.asMap().entrySet()) { for (FetchReplica r : entry.getValue()) logger.trace("{}: range source local range for keyspace {}", description, r.remote, r.local, keyspaceName); } } }
Source:
private Optional<byte[]> getId(byte[] lookupkey, int numIdBytes) throws IOException, InterruptedException { Result result = WithHTable.get(pool, lookupTable, new Get(lookupkey)); final byte[] columnVal = result.getValue(cf, QUALIFIER); int tries = 0; while (tries < MAX_COMPAT_TRIES) { if (columnVal != null) { int statusOrdinal = columnVal[0]; Status status = Status.values()[statusOrdinal]; if (log.isDebugEnabled()) { log.debug("Entry status is " + status); } switch (status) { case ALLOCATED: byte[] id = Util.trailingBytes(columnVal, numIdBytes); if (log.isDebugEnabled()) { log.debug("Already allocated, returning " + Hex.encodeHexString(id)); } return Optional.of(id); case ALLOCATING: Thread.sleep(COMPAT_RETRY_SLEEP); tries++; break; default: throw new RuntimeException("Unexpected column value " + Arrays.toString(columnVal)); } } else { return Optional.absent(); } } throw new RuntimeException(String.format("Row %s was still 'ALLOCATING' after %d millis. Something is wrong.", Bytes.toString(lookupkey), MAX_COMPAT_TRIES * COMPAT_RETRY_SLEEP)); }

Target:
private Optional<byte[]> getId(byte[] lookupkey, int numIdBytes) throws IOException, InterruptedException { final TimerContext timer = idGetTime.time(); Result result = WithHTable.get(pool, lookupTable, new Get(lookupkey)); final byte[] columnVal = result.getValue(cf, QUALIFIER); int tries = 0; while (tries < MAX_COMPAT_TRIES) { if (columnVal != null) { int statusOrdinal = columnVal[0]; Status status = Status.values()[statusOrdinal]; if (log.isDebugEnabled()) { log.debug("Entry status is " + status); } switch (status) { case ALLOCATED: byte[] id = Util.trailingBytes(columnVal, numIdBytes); if (log.isDebugEnabled()) { log.debug("Already allocated, returning " + Hex.encodeHexString(id)); } timer.stop(); return Optional.of(id); case ALLOCATING: allocatingSleeps.mark(); Thread.sleep(COMPAT_RETRY_SLEEP); tries++; break; default: throw new RuntimeException("Unexpected column value " + Arrays.toString(columnVal)); } } else { timer.stop(); return Optional.absent(); } } throw new RuntimeException(String.format("Row %s was still 'ALLOCATING' after %d millis. Something is wrong.", Bytes.toString(lookupkey), MAX_COMPAT_TRIES * COMPAT_RETRY_SLEEP)); }
Source:
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }

Target:
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
Source:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()).boxed() .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .map(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }

Target:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()) .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .mapToObj(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }
Source:
public void evaluate() throws Throwable { if (null != previous) { previous.evaluate(); } for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }

Target:
public void evaluate() throws Throwable { for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }
Source:
protected void showCaseData(String selection, String[] selectionArgs) { ListView la = (ListView)this.findViewById(R.id.list_view); Cursor c = this.managedQuery(Uri.parse("content://org.commcare.dalvik.case/casedb/case"), null, selection, selectionArgs, null); final SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, c, new String[] {"case_name", "case_id"}, new int[] { android.R.id.text1, android.R.id.text2}); la.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseType = cursor.getString(cursor.getColumnIndex("case_type")); CaseMediaActivity.this.showCaseData("case_type = ? AND\nstatus=?", new String[] { caseType,"open" }); return true; } }); la.setAdapter(sca); la.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseId = cursor.getString(cursor.getColumnIndex("case_id")); CaseMediaActivity.this.moveToMediaAdapter(caseId); } }); }

Target:
private void showCaseData(String selection, String[] selectionArgs) { ListView la = (ListView)this.findViewById(R.id.list_view); Cursor c = this.managedQuery(Uri.parse(CASE_URI_ROOT + "case"), null, selection, selectionArgs, null); final SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, c, new String[] {"case_name", "case_id"}, new int[] { android.R.id.text1, android.R.id.text2}); la.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseType = cursor.getString(cursor.getColumnIndex("case_type")); CaseMediaActivity.this.showCaseData("case_type = ? AND\nstatus=?", new String[] { caseType,"open" }); return true; } }); la.setAdapter(sca); la.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseId = cursor.getString(cursor.getColumnIndex("case_id")); CaseMediaActivity.this.moveToMediaAdapter(caseId); } }); }
Source:
public Optional<IgniteableData> createFrom(DataHolder dataHolder) { if (supports(dataHolder)) { final int fireTicks = ((net.minecraft.entity.Entity) dataHolder).fire; final int fireDelay = ((net.minecraft.entity.Entity) dataHolder).fireResistance; return Optional.<IgniteableData>of(new SpongeIgniteableData(fireTicks, fireDelay)); } return Optional.absent(); }

Target:
public Optional<IgniteableData> createFrom(DataHolder dataHolder) { if (supports(dataHolder)) { if (dataHolder instanceof Entity) { final int fireTicks = ((Entity) dataHolder).fire; final int fireDelay = ((Entity) dataHolder).fireResistance; return Optional.<IgniteableData>of(new SpongeIgniteableData(fireTicks, fireDelay)); } } return Optional.absent(); }
Source:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.Ovm) { s_logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() != HypervisorType.Ovm) { continue; } if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (AgentUnavailableException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable (Operation Cancelled)"); } continue; } if (answer != null && answer.getResult()) { return true; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }

Target:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.Ovm) { s_logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() != HypervisorType.Ovm) { continue; } if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (AgentUnavailableException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancelling because " + h.toString() + " is unavailable (Operation Cancelled)"); } break; } if (answer != null && answer.getResult()) { return true; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }
Source:
public PinotQueryGeneratorContext visitTopN(TopNNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); checkSupported(preferBrokerQueries, "Cannot push topn in segment mode"); checkSupported(node.getStep().equals(TopNNode.Step.SINGLE), "Can only push single logical topn in"); return context.withTopN(PushdownUtils.getOrderingScheme(node), node.getCount()).withOutputColumns(node.getOutputVariables()); }

Target:
public PinotQueryGeneratorContext visitTopN(TopNNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); checkSupported(preferBrokerQueries, "Cannot push topn in segment mode"); checkSupported(node.getStep().equals(TopNNode.Step.SINGLE), "Can only push single logical topn in"); return context.withTopN(getOrderingScheme(node), node.getCount()).withOutputColumns(node.getOutputVariables()); }
Source:
public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = cm.getOwnerConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; ClientPrincipal principal = cm.getPrincipal(); final String uuid = principal != null ? principal.getUuid() : null; return new ClientImpl(uuid, inetSocketAddress, client.getName(), client.getClientConfig().getAttributes()); }

Target:
public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = cm.getOwnerConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; ClientPrincipal principal = cm.getPrincipal(); final String uuid = principal != null ? principal.getUuid() : null; return new ClientImpl(uuid, inetSocketAddress, client.getName(), attributes); }
Source:
protected <T extends VMInstanceVO> boolean changeState(final T vm, final Event event, final Long hostId, final ItWorkVO work, final Step step) throws NoTransitionException { Step previousStep = null; if (work != null) { previousStep = work.getStep(); _workDao.updateStep(work, step); } boolean result = false; try { result = stateTransitTo(vm, event, hostId); return result; } finally { if (!result && previousStep != null) { _workDao.updateStep(work, previousStep); } } }

Target:
protected <T extends VMInstanceVO> boolean changeState(final T vm, final Event event, final Long hostId, final ItWorkVO work, final Step step) throws NoTransitionException { Step previousStep = null; if (work != null) { previousStep = work.getStep(); _workDao.updateStep(work, step); } boolean result = false; try { result = stateTransitTo(vm, event, hostId); return result; } finally { if (!result && work != null) { _workDao.updateStep(work, previousStep); } } }
Source:
public void shouldBlockUntilFailedCompletion() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); final Throwable expectedError = new Throwable(); runSeparateTestThread(() -> { try { testCallback.waitForGet(); testCallback.onCompletion(expectedError, null); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); try { testCallback.get(); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } assertEquals(0, testCallback.numberOfConversions()); assertTrue(testCallback.isDone()); if (testThreadException.get() != null) { throw testThreadException.get(); } }

Target:
public void shouldBlockUntilFailedCompletion() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); final Throwable expectedError = new Throwable(); executor.submit(() -> { try { testCallback.waitForGet(); testCallback.onCompletion(expectedError, null); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); try { testCallback.get(); fail("Expected ExecutionException"); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } assertEquals(0, testCallback.numberOfConversions()); assertTrue(testCallback.isDone()); if (testThreadException.get() != null) { throw testThreadException.get(); } }
Source:
public QueueServiceClientBuilder() { retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; policies = new ArrayList<>(); configuration = ConfigurationManager.getConfiguration(); retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; }

Target:
public QueueServiceClientBuilder() { retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; policies = new ArrayList<>(); configuration = ConfigurationManager.getConfiguration(); }
Source:
static long nanoToMicro(long nano) { return (long) Math.ceil(nano / (double) 1000); }

Target:
static long nanoToMicro(long nano) { return Math.max(1, (long) Math.ceil(nano / (double) 1000)); }
Source:
private void notifyToLocatorActivity(BDLocation bdloc) { if (mLocationListener != null) { MyLocationData locData = new MyLocationData.Builder() .accuracy(bdloc.getRadius()) .direction(100).latitude(bdloc.getLatitude()) .longitude(bdloc.getLongitude()).build(); Location aLoc = new Location("BaiduMap"); aLoc.setLongitude(bdloc.getLongitude()); aLoc.setLatitude(bdloc.getLatitude()); mLocationListener.onLocationChanged(aLoc); } }

Target:
private void notifyToLocatorActivity(BDLocation bdloc) { if (mLocationListener != null) { Location aLoc = new Location("BaiduMap"); aLoc.setLongitude(bdloc.getLongitude()); aLoc.setLatitude(bdloc.getLatitude()); mLocationListener.onLocationChanged(aLoc); } }
Source:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { discovering = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }

Target:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", xbeeDevice.toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { discovering = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self response: {}.", xbeeDevice.toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }
Source:
public void close() { instance = null; if (isolatedThread != null) { isolatedThread.setContextClassLoader(previousContextClassLoader); } if (!reusableClassLoader) { ClassLoaderIsolatedSystemProperties.getInstance().stopIsolateClassLoader(sandboxClassLoader); if (sandboxClassLoader instanceof AutoCloseable) { try { ((AutoCloseable) sandboxClassLoader).close(); } catch (Exception e) { new TalendRuntimeException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } } } sandboxClassLoader = null; previousContextClassLoader = null; isolatedThread = null; isClosed = true; }

Target:
public void close() { instance = null; if (isolatedThread != null) { isolatedThread.setContextClassLoader(previousContextClassLoader); } if (!reusableClassLoader) { ClassLoaderIsolatedSystemProperties.getInstance().stopIsolateClassLoader(sandboxClassLoader); if (sandboxClassLoader instanceof AutoCloseable) { try { ((AutoCloseable) sandboxClassLoader).close(); } catch (Exception e) { TalendRuntimeException.createUnexpectedException(e); } } } sandboxClassLoader = null; previousContextClassLoader = null; isolatedThread = null; isClosed = true; }
Source:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = Arrays.stream( entityDictionary.getAttributeOrRelationAnnotation( cls, MetricAggregation.class, metricField ).aggregations() ) .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); String columnName = metricField; if (entityDictionary.attributeOrRelationAnnotationExists(cls, metricField, javax.persistence.Column.class)) { columnName = entityDictionary .getAttributeOrRelationAnnotation(cls, javax.persistence.Column.class, metricField).name(); } return new AggregatedMetric( this, metricField, metaData, fieldType, aggregations, columnName ); }

Target:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = getAggregations(metricField, cls, entityDictionary); return new AggregatedMetric( this, metricField, metaData, fieldType, aggregations ); }
Source:
public Symbol visitIntervalLiteral(IntervalLiteral node, ExpressionAnalysisContext context) { String value = node.getValue(); if (value == null || value.isEmpty() || value.isBlank()) { throw new IllegalArgumentException("Invalid value " + value); } IntervalParser.Precision start = INTERVAL_FIELDS.get(node.getStartField()); IntervalParser.Precision end = node.getEndField() == null ? null : INTERVAL_FIELDS.get(node.getEndField()); Period period = IntervalParser.apply(value, start, end); if (node.getSign() == IntervalLiteral.Sign.MINUS) { period = period.negated(); } return Literal.newInterval(period); }

Target:
public Symbol visitIntervalLiteral(IntervalLiteral node, ExpressionAnalysisContext context) { String value = node.getValue(); IntervalParser.Precision start = INTERVAL_FIELDS.get(node.getStartField()); IntervalParser.Precision end = node.getEndField() == null ? null : INTERVAL_FIELDS.get(node.getEndField()); Period period = IntervalParser.apply(value, start, end); if (node.getSign() == IntervalLiteral.Sign.MINUS) { period = period.negated(); } return Literal.newInterval(period); }
Source:
protected void beforeExecute() { builder.addImport(builder.build().getPackageName().replace("queries", "") + getContextType()); addBaseClassAndConstructor(); }

Target:
protected void beforeExecute() { addBaseClassAndConstructor(); }
Source:
public void setLocale(String locale) { titleText.setLocale(locale); subtitleText.setLocale(locale); LayoutParams dividerParams = (LayoutParams) divider.getLayoutParams(); dividerParams.gravity = isLangRTL(locale) ? Gravity.RIGHT : Gravity.LEFT; divider.setLayoutParams(dividerParams); FrameLayout.LayoutParams pencilParams = (FrameLayout.LayoutParams) editPencil.getLayoutParams(); pencilParams.gravity = Gravity.BOTTOM | (isLangRTL(locale) ? Gravity.LEFT : Gravity.RIGHT); editPencil.setLayoutParams(pencilParams); int subtitlePadding = editPencil.getWidth(); subtitleText.setPadding(isLangRTL(locale) ? subtitlePadding : 0, subtitleText.getPaddingTop(), isLangRTL(locale) ? 0 : subtitlePadding, subtitleText.getPaddingBottom()); }

Target:
public void setLocale(String locale) { titleText.setLocale(locale); subtitleText.setLocale(locale); LinearLayout.LayoutParams dividerParams = (LinearLayout.LayoutParams) divider.getLayoutParams(); dividerParams.gravity = isLangRTL(locale) ? Gravity.RIGHT : Gravity.LEFT; divider.setLayoutParams(dividerParams); FrameLayout.LayoutParams pencilParams = (FrameLayout.LayoutParams) editPencil.getLayoutParams(); pencilParams.gravity = Gravity.BOTTOM | (isLangRTL(locale) ? Gravity.LEFT : Gravity.RIGHT); int subtitlePadding = editPencil.getWidth(); subtitleText.setPadding(isLangRTL(locale) ? subtitlePadding : 0, subtitleText.getPaddingTop(), isLangRTL(locale) ? 0 : subtitlePadding, subtitleText.getPaddingBottom()); }
Source:
public static void loadRuntimeConfiguration(RuntimeInfo runtimeInfo) throws IOException { RuntimeEL.runtimeInfo = runtimeInfo; Configuration configuration = new Configuration(); File configFile = new File(runtimeInfo.getConfigDir(), SDC_PROPERTIES); if (configFile.exists()) { try(FileReader reader = new FileReader(configFile)) { configuration.load(reader); } catch (IOException ex) { LOG.error("Error loading configuration file : {}", configFile, ex.getMessage()); throw new RuntimeException(ex); } AUTH_TOKEN = runtimeInfo.getAppAuthToken(); HOSTNAME = configuration.get(WebServerTask.HTTP_BIND_HOST, defaultHostnameMethod); RUNTIME_CONF_PROPS = new Properties(); String runtimeConfLocation = configuration.get(RUNTIME_CONF_LOCATION_KEY, RUNTIME_CONF_LOCATION_DEFAULT); if(runtimeConfLocation.equals(RUNTIME_CONF_LOCATION_DEFAULT)) { for(String confName : configuration.getNames()) { if(confName.startsWith(RUNTIME_CONF_PREFIX)) { RUNTIME_CONF_PROPS.put(confName.substring(RUNTIME_CONF_PREFIX.length()).trim(), configuration.get(confName, (String)null)); } } } else { File runtimeConfFile = new File(runtimeInfo.getConfigDir(), runtimeConfLocation); try (FileInputStream fileInputStream = new FileInputStream(runtimeConfFile)) { RUNTIME_CONF_PROPS.load(fileInputStream); } catch (IOException e) { LOG.error("Could not read '{}': {}", runtimeConfFile.getAbsolutePath(), e.toString(), e); throw e; } } } else { LOG.error("Error did not find sdc.properties at expected location: {}", configFile); } }

Target:
public static void loadRuntimeConfiguration(RuntimeInfo runtimeInfo) throws IOException { RuntimeEL.runtimeInfo = runtimeInfo; Configuration configuration = new Configuration(); File configFile = new File(runtimeInfo.getConfigDir(), SDC_PROPERTIES); if (configFile.exists()) { try(FileReader reader = new FileReader(configFile)) { configuration.load(reader); } catch (IOException ex) { LOG.error("Error loading configuration file : {}", configFile, ex.getMessage()); throw new RuntimeException(ex); } AUTH_TOKEN = runtimeInfo.getAppAuthToken(); HOSTNAME = configuration.get(WebServerTask.HTTP_BIND_HOST, null); if (HOSTNAME==null) { HOSTNAME = configuration.get(WebServerTask.HTTP_BIND_HOST,defaultHostnameMethod.get()); } RUNTIME_CONF_PROPS = new Properties(); String runtimeConfLocation = configuration.get(RUNTIME_CONF_LOCATION_KEY, RUNTIME_CONF_LOCATION_DEFAULT); if(runtimeConfLocation.equals(RUNTIME_CONF_LOCATION_DEFAULT)) { for(String confName : configuration.getNames()) { if(confName.startsWith(RUNTIME_CONF_PREFIX)) { RUNTIME_CONF_PROPS.put(confName.substring(RUNTIME_CONF_PREFIX.length()).trim(), configuration.get(confName, (String)null)); } } } else { File runtimeConfFile = new File(runtimeInfo.getConfigDir(), runtimeConfLocation); try (FileInputStream fileInputStream = new FileInputStream(runtimeConfFile)) { RUNTIME_CONF_PROPS.load(fileInputStream); } catch (IOException e) { LOG.error("Could not read '{}': {}", runtimeConfFile.getAbsolutePath(), e.toString(), e); throw e; } } } else { LOG.error("Error did not find sdc.properties at expected location: {}", configFile); } }
Source:
public static List<RowExpression> extractPredicates(Form form, RowExpression expression) { if (expression instanceof SpecialFormExpression && ((SpecialFormExpression) expression).getForm() == form) { SpecialFormExpression specialFormExpression = (SpecialFormExpression) expression; if (specialFormExpression.getArguments().size() != 2) { throw new IllegalStateException("logical binary expression requires exactly 2 operands"); } List<RowExpression> predicates = new ArrayList<>(); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(0))); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(1))); return predicates; } return Collections.singletonList(expression); }

Target:
public static List<RowExpression> extractPredicates(Form form, RowExpression expression) { if (expression instanceof SpecialFormExpression && ((SpecialFormExpression) expression).getForm() == form) { SpecialFormExpression specialFormExpression = (SpecialFormExpression) expression; if (specialFormExpression.getArguments().size() != 2) { throw new IllegalStateException("logical binary expression requires exactly 2 operands"); } List<RowExpression> predicates = new ArrayList<>(); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(0))); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(1))); return Collections.unmodifiableList(predicates); } return Collections.singletonList(expression); }
Source:
private void addSenMLRecord(String recordName, LwM2mResource resource, Object value) { ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); SenMLRecord record = new SenMLRecord(); String bn = requestPath.toString(); String n = recordName == null ? "" : recordName; if (records.isEmpty()) { if (!requestPath.isResource()) { bn += "/"; } record.setBaseName(bn); } record.setName(n); LwM2mPath lwM2mResourcePath = new LwM2mPath(bn + n); Object convertedValue = converter.convertValue(value, resource.getType(), expectedType, lwM2mResourcePath); setResourceValue(convertedValue, expectedType, lwM2mResourcePath, record); records.add(record); }

Target:
private void addSenMLRecord(String recordName, LwM2mResource resource, Object value) { ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); SenMLRecord record = new SenMLRecord(); String bn = requestPath.toString(); String n = recordName == null ? "" : recordName; if (records.isEmpty()) { if (!n.isEmpty()) { bn += "/"; } record.setBaseName(bn); } record.setName(n); LwM2mPath lwM2mResourcePath = new LwM2mPath(bn + n); Object convertedValue = converter.convertValue(value, resource.getType(), expectedType, lwM2mResourcePath); setResourceValue(convertedValue, expectedType, lwM2mResourcePath, record); records.add(record); }
Source:
private void setTemperatureMeasurementTimerInterval(int measurementIntervalValueSeconds) { timer = new CountDownTimer(30000, measurementIntervalValueSeconds * 1000) { @Override public void onTick(long millisUntilFinished) { mDelegate.sendNotificationToDevices(mTemperatureMeasurementCharacteristic); } @Override public void onFinish() { timer.start(); } }.start(); final String message = String.format(getString(R.string.sendingNotifications), measurementIntervalValueSeconds); getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } }); }

Target:
private void setTemperatureMeasurementTimerInterval(int measurementIntervalValueSeconds) { mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mDelegate.sendNotificationToDevices(mTemperatureMeasurementCharacteristic); } }); } }, 0 , measurementIntervalValueSeconds * 1000); }
Source:
public boolean mousePressed(Minecraft mc, int x, int y) { boolean b = parent.blockMouseInput ? false : super.mousePressed(mc, x, y); if (b) parent.tileentity.setInputMode(side, EnumConnectionType.values()[(mode.ordinal() + 1) % 4]); return b; }

Target:
public boolean mousePressed(Minecraft mc, int x, int y) { boolean b = !parent.blockMouseInput && super.mousePressed(mc, x ,y); if (b) { List<EnumConnectionType> supported = EnumConnectionType.getSupportedList(parent.getCircuitData().maximumIOSize()); EnumConnectionType next = supported.get((supported.indexOf(mode) + 1) % supported.size()); parent.tileentity.setInputMode(side, next); } return b; }
Source:
private static Object tryToMakeCompatibleArray( final Class<?> expectedComponentClz, final Class<?> inputComponentClz, Object param) throws VoltTypeException { int inputLength = Array.getLength(param); if (inputComponentClz == expectedComponentClz) { return param; } else if (inputLength == 0) { return Array.newInstance(expectedComponentClz, 0); } else if ((inputComponentClz == byte[].class || inputComponentClz == Byte[].class) && (expectedComponentClz == String.class)) { String[] values = new String[inputLength]; for (int i = 0; i < inputLength; i++) { try { values[i] = new String((byte[]) Array.get(param, i), "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new VoltTypeException( "tryScalarMakeCompatible: Unsupported encoding:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == byte[].class || expectedComponentClz == Byte[].class )) { byte[][] values = new byte[inputLength][]; Byte[][] boxvalues = new Byte[inputLength][]; for (int i = 0; i < inputLength; i++) { values[i] = Encoder.hexDecode((String) Array.get(param, i)); boxvalues[i] = ArrayUtils.toObject( values[i] ); } if (expectedComponentClz == byte[].class) return values; else return boxvalues; } else { throw new VoltTypeException( "tryScalarMakeCompatible: Unable to match parameter array:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } }

Target:
private static Object tryToMakeCompatibleArray( final Class<?> expectedComponentClz, final Class<?> inputComponentClz, Object param) throws VoltTypeException { int inputLength = Array.getLength(param); if (inputComponentClz == expectedComponentClz) { return param; } else if (inputLength == 0) { return Array.newInstance(expectedComponentClz, 0); } else if (isByteArrayClass(inputComponentClz) && (expectedComponentClz == String.class)) { String[] values = new String[inputLength]; for (int i = 0; i < inputLength; i++) { try { values[i] = new String((byte[]) Array.get(param, i), "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new VoltTypeException( "tryScalarMakeCompatible: Unsupported encoding:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == byte[].class)) { byte[][] values = new byte[inputLength][]; for (int i = 0; i < inputLength; i++) { values[i] = Encoder.hexDecode((String) Array.get(param, i)); } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == Byte[].class)) { Byte[][] boxvalues = new Byte[inputLength][]; for (int i = 0; i < inputLength; i++) { boxvalues[i] = ArrayUtils.toObject( Encoder.hexDecode((String) Array.get(param, i)) ); } return boxvalues; } else { throw new VoltTypeException( "tryScalarMakeCompatible: Unable to match parameter array:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.save_pin) { if (client.getPosition() == null) { Toaster.show(findViewById(android.R.id.content), getString(R.string.you_should_drop_client_pin)); return false; } mPinPointClientPresenter.updateGpsData(clientId, new GpsCoordinatesRequest(client .getPosition())); } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.save_pin) { if (client.getPosition() == null) { Toaster.show(findViewById(android.R.id.content), getString(R.string.drop_client_pin)); return false; } mPinPointClientPresenter.updateGpsData(clientId, new GpsCoordinatesRequest(client .getPosition())); } return super.onOptionsItemSelected(item); }
Source:
private int getModelOrderFromConnectedEdges(final LNode n) { List<LPort> ports = n.getPorts(); if (ports.size() > 0) { LEdge edge = null; for (LPort lPort : ports) { if (lPort.getIncomingEdges().size() > 0) { edge = lPort.getIncomingEdges().get(0); break; } } if (edge == null) { return Integer.MAX_VALUE; } return edge.getProperty(InternalProperties.MODEL_ORDER); } return Integer.MAX_VALUE; }

Target:
private int getModelOrderFromConnectedEdges(final LNode n) { LPort sourcePort = n.getPorts().stream().filter(p -> !p.getIncomingEdges().isEmpty()).findFirst().orElse(null); if (sourcePort != null) { LEdge edge = sourcePort.getIncomingEdges().get(0); if (edge != null) { return edge.getProperty(InternalProperties.MODEL_ORDER); } } return Integer.MAX_VALUE; }
Source:
public void testInvocation() throws Exception { MockRoutingTableChangeListener routingTableChangeListener = new TestRoutingTableProvider().new MockRoutingTableChangeListener(); _routingTableProvider_default.addRoutingTableChangeListener(routingTableChangeListener, null); AssertJUnit.assertTrue(routingTableChangeListener.routingTableChangeReceived); }

Target:
public void testInvocation() throws Exception { MockRoutingTableChangeListener routingTableChangeListener = new MockRoutingTableChangeListener(); _routingTableProvider_default .addRoutingTableChangeListener(routingTableChangeListener, null, true); Assert.assertTrue(TestHelper.verify(() -> { if (!routingTableChangeListener.routingTableChangeReceived) { return false; } return true; }, TestHelper.WAIT_DURATION)); }
Source:
public void generateDataBeans() { LicenseHeaders licenseHeader = new LicenseHeaders("ASLv2"); File[] inputFiles = getInputFiles(); try { GoraCompiler.compileSchema(inputFiles, BEAN_DESTINATION_DIR, licenseHeader); } catch (IOException e) { } }

Target:
public static void generateDataBeans() { LicenseHeaders licenseHeader = new LicenseHeaders("ASLv2"); File[] inputFiles = getInputFiles(); try { GoraCompiler.compileSchema(inputFiles, Constants.BEAN_DESTINATION_DIR, licenseHeader); } catch (IOException e) { LOG.info("There is a problem generating Data Beans \n {}", e.getMessage(), e); } }
Source:
private void splitMultipleDeclarations(Node var) { checkState(var.isVar() || var.isLet() || var.isConst()); while (var.getSecondChild() != null) { Node newVar; Node nameToSplit = var.removeFirstChild(); switch (var.getToken()) { default: case VAR: newVar = IR.var(nameToSplit); break; case LET: newVar = IR.var(nameToSplit); break; case CONST: newVar = IR.var(nameToSplit); break; } newVar.useSourceInfoFrom(var); var.getParent().addChildBefore(newVar, var); } }

Target:
private void splitMultipleDeclarations(Node var) { checkState(var.isVar() || var.isLet() || var.isConst()); while (var.getSecondChild() != null) { Node newVar = new Node(var.getToken(), var.removeFirstChild()); newVar.useSourceInfoFrom(var); var.getParent().addChildBefore(newVar, var); } }
Source:
public void onPause() { disposables.dispose(); }

Target:
public void onPause() { compositeDisposable.clear(); }
Source:
private void registerRepositoryInfoType(NodeTypeManager typeManager) throws RepositoryException { NodeTypeTemplate type = typeManager.createNodeTypeTemplate(); type.setName("cmis:repository"); type.setAbstract(false); type.setMixin(true); type.setOrderableChildNodes(true); type.setQueryable(true); type.setDeclaredSuperTypeNames(new String[]{"nt:folder"}); PropertyDefinitionTemplate vendorName = typeManager.createPropertyDefinitionTemplate(); vendorName.setAutoCreated(false); vendorName.setName("cmis:vendorName"); vendorName.setMandatory(false); type.getPropertyDefinitionTemplates().add(vendorName); PropertyDefinitionTemplate productName = typeManager.createPropertyDefinitionTemplate(); productName.setAutoCreated(false); productName.setName("cmis:productName"); productName.setMandatory(false); type.getPropertyDefinitionTemplates().add(productName); PropertyDefinitionTemplate productVersion = typeManager.createPropertyDefinitionTemplate(); productVersion.setAutoCreated(false); productVersion.setName("cmis:productVersion"); productVersion.setMandatory(false); type.getPropertyDefinitionTemplates().add(productVersion); NodeTypeDefinition[] nodeDefs = new NodeTypeDefinition[] {type}; typeManager.registerNodeTypes(nodeDefs, true); }

Target:
private void registerRepositoryInfoType(NodeTypeManager typeManager) throws RepositoryException { NodeTypeTemplate type = typeManager.createNodeTypeTemplate(); type.setName("cmis:repository"); type.setAbstract(false); type.setMixin(true); type.setOrderableChildNodes(true); type.setQueryable(true); type.setDeclaredSuperTypeNames(new String[]{JcrConstants.NT_FOLDER}); PropertyDefinitionTemplate vendorName = typeManager.createPropertyDefinitionTemplate(); vendorName.setAutoCreated(false); vendorName.setName("cmis:vendorName"); vendorName.setMandatory(false); type.getPropertyDefinitionTemplates().add(vendorName); PropertyDefinitionTemplate productName = typeManager.createPropertyDefinitionTemplate(); productName.setAutoCreated(false); productName.setName("cmis:productName"); productName.setMandatory(false); type.getPropertyDefinitionTemplates().add(productName); PropertyDefinitionTemplate productVersion = typeManager.createPropertyDefinitionTemplate(); productVersion.setAutoCreated(false); productVersion.setName("cmis:productVersion"); productVersion.setMandatory(false); type.getPropertyDefinitionTemplates().add(productVersion); NodeTypeDefinition[] nodeDefs = new NodeTypeDefinition[]{type}; typeManager.registerNodeTypes(nodeDefs, true); }
Source:
private void init() { mZoomableController = createZoomableController(); mZoomableController.setListener(mZoomableListener); mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper); mTapGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onSingleTapConfirmed(MotionEvent e) { return false; } @Override public boolean onDoubleTap(MotionEvent e) { float maxScaleFactor = ((DefaultZoomableController) mZoomableController).getMaxScaleFactor(); RectF bounds = ((DefaultZoomableController) mZoomableController).getImageBounds(); float x = e.getX(); float y = e.getY(); PointF imagePoint = new PointF((x - bounds.left) / bounds.width(), (y - bounds.top) / bounds.height()); float scaleFactor = mZoomableController.getScaleFactor() < maxScaleFactor ? maxScaleFactor : ((DefaultZoomableController) mZoomableController).getMinScaleFactor(); if (mZoomableController instanceof AbstractAnimatedZoomableController) { ((AbstractAnimatedZoomableController) mZoomableController).zoomToPoint(scaleFactor, imagePoint, new PointF(x, y), DefaultZoomableController.LIMIT_ALL, 200, null); } else { ((DefaultZoomableController) mZoomableController).zoomToPoint(scaleFactor, imagePoint, new PointF(x, y)); } return true; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } }); }

Target:
private void init() { mZoomableController = createZoomableController(); mZoomableController.setListener(mZoomableListener); mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper); }
Source:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (!courseData.getCourse().getCoursewareAccess().hasAccess()) { return; } inflater.inflate(R.menu.course_dashboard_menu, menu); if (environment.getConfig().isCourseSharingEnabled()) { menu.findItem(R.id.menu_item_share).setVisible(true); } else { menu.findItem(R.id.menu_item_share).setVisible(false); } handleDownloadProgressMenuItem(menu); }

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.course_dashboard_menu, menu); if (environment.getConfig().isCourseSharingEnabled()) { menu.findItem(R.id.menu_item_share).setVisible(true); } else { menu.findItem(R.id.menu_item_share).setVisible(false); } handleDownloadProgressMenuItem(menu); }