auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ExtractionFn getExtractionFn() { final LookupExtractor lookupExtractor = Strings.isNullOrEmpty(name) ? this.lookup : (LookupExtractor) Preconditions.checkNotNull( this.lookupReferencesManager.get(name).get(), "can not find lookup with name [%s]", name ); return new LookupExtractionFn( lookupExtractor, retainMissingValue, replaceMissingValueWith, lookupExtractor.isOneToOne(), optimize ); }

Target:
public ExtractionFn getExtractionFn() { final LookupExtractor lookupExtractor = Strings.isNullOrEmpty(name) ? this.lookup : Preconditions.checkNotNull( lookupReferencesManager.get(name), "Lookup [%s] not found", name ).get(); return new LookupExtractionFn( lookupExtractor, retainMissingValue, replaceMissingValueWith, lookupExtractor.isOneToOne(), optimize ); }
Source:
private String unescape(String s) throws URISyntaxException { if (s == null) return null; if (getScheme() == null) return s; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } ByteArrayOutputStream os = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 1 > bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int ascValue = Integer.parseInt(s.substring(i+1,i+3),16); os.write(ascValue); i += 2; } else os.write(c); } return RawParseUtils.decode(os.toByteArray()); }

Target:
private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length); for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 2 > bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int ascValue = Integer.parseInt(s.substring(i + 1, i + 3), 16); os.write(ascValue); i += 2; } else os.write(c); } return RawParseUtils.decode(os.toByteArray()); }
Source:
public void stackCommand(DocumentEventContext docCtx, String eventId) { DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } if ("/".equals(doc.getPathAsString())) { if (log.isDebugEnabled()) { log.debug("Skip indexing command for root document"); } if (eventId.equals(DOCUMENT_SECURITY_UPDATED)) { if (log.isDebugEnabled()) { log.debug("Indexing root document children to update their permissions"); } DocumentModelList children = doc.getCoreSession().getChildren(doc.getRef()); children.forEach(child -> stackCommand(doc, docCtx, eventId)); } } else { stackCommand(doc, docCtx, eventId); } }

Target:
public void stackCommand(DocumentEventContext docCtx, String eventId) { DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } if ("/".equals(doc.getPathAsString())) { if (log.isDebugEnabled()) { log.debug("Skip indexing command for root document"); } if (eventId.equals(DOCUMENT_SECURITY_UPDATED)) { if (log.isDebugEnabled()) { log.debug("Indexing root document children to update their permissions"); } DocumentModelList children = doc.getCoreSession().getChildren(doc.getRef()); children.forEach(child -> stackCommand(child, docCtx, eventId)); } } else { stackCommand(doc, docCtx, eventId); } }
Source:
public static List<ItemStack> getItemStackFromBlock(World world, int i, int j, int k) { Block block = Block.blocksList[world.getBlockId(i, j, k)]; if (block == null) return null; if (block.isAirBlock(world, i, j, k)) return null; int meta = world.getBlockMetadata(i, j, k); ArrayList<ItemStack> dropsList = block.getBlockDropped(world, i, j, k, meta, 0); float dropChance = ForgeEventFactory.fireBlockHarvesting(dropsList, world, block, i, j, k, world.getBlockMetadata(i, j, k), 0, 1.0F, false, null); ArrayList<ItemStack> returnList = new ArrayList<ItemStack>(); for (ItemStack s : dropsList) { if (world.rand.nextFloat() <= dropChance) { returnList.add(s); } } return returnList; }

Target:
public static List<ItemStack> getItemStackFromBlock(World world, int i, int j, int k) { Block block = Block.blocksList[world.getBlockId(i, j, k)]; if (block == null) return null; if (block.isAirBlock(world, i, j, k)) return null; int meta = world.getBlockMetadata(i, j, k); ArrayList<ItemStack> dropsList = block.getBlockDropped(world, i, j, k, meta, 0); float dropChance = ForgeEventFactory.fireBlockHarvesting(dropsList, world, block, i, j, k, meta, 0, 1.0F, false, null); ArrayList<ItemStack> returnList = new ArrayList<ItemStack>(); for (ItemStack s : dropsList) { if (world.rand.nextFloat() <= dropChance) { returnList.add(s); } } return returnList; }
Source:
private void flush(List<String> cacheNames) throws UnprocessableEntityException, AuthException { List<CacheResource> cacheResources = new ArrayList<>(); for (String n : cacheNames) { String pluginName = "gerrit"; String cacheName = n; int i = cacheName.lastIndexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Cache<?, ?> cache = cacheMap.get(pluginName, cacheName); if (cache != null) { cacheResources.add(new CacheResource(pluginName, cacheName, cache)); } else { throw new UnprocessableEntityException(String.format( "cache %s not found", n)); } } for (CacheResource rsrc : cacheResources) { flushCache.get().apply(rsrc, new FlushCache.Input()); } }

Target:
private void flush(List<String> cacheNames) throws UnprocessableEntityException, AuthException { List<CacheResource> cacheResources = new ArrayList<>(cacheNames.size()); for (String n : cacheNames) { String pluginName = "gerrit"; String cacheName = n; int i = cacheName.lastIndexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Cache<?, ?> cache = cacheMap.get(pluginName, cacheName); if (cache != null) { cacheResources.add(new CacheResource(pluginName, cacheName, cache)); } else { throw new UnprocessableEntityException(String.format( "cache %s not found", n)); } } for (CacheResource rsrc : cacheResources) { flushCache.apply(rsrc, null); } }
Source:
protected ClientHttpResponse run() throws Exception { final RequestContext context = RequestContext.getCurrentContext(); RQ request = createRequest(); RS response; if (!isExecuteWithLoadBalancer() && request!= null && request.isRetriable()) { response = this.client.execute(request, config); } else { response = this.client.executeWithLoadBalancer(request, config); } context.set("ribbonResponse", response); if (this.isResponseTimedOut()) { if (response != null) { response.close(); } } return new RibbonHttpResponse(response); }

Target:
protected ClientHttpResponse run() throws Exception { final RequestContext context = RequestContext.getCurrentContext(); RQ request = createRequest(); RS response; boolean retryableClient = this.client instanceof AbstractLoadBalancingClient && ((AbstractLoadBalancingClient)this.client).isClientRetryable((ContextAwareRequest)request); if (retryableClient) { response = this.client.execute(request, config); } else { response = this.client.executeWithLoadBalancer(request, config); } context.set("ribbonResponse", response); if (this.isResponseTimedOut()) { if (response != null) { response.close(); } } return new RibbonHttpResponse(response); }
Source:
public void onBlogClicked(Object item) { long blogId; long feedId; if (item instanceof ReaderRecommendedBlog) { ReaderRecommendedBlog blog = (ReaderRecommendedBlog) item; blogId = blog.blogId; feedId = 0; } else if (item instanceof ReaderBlog) { ReaderBlog blog = (ReaderBlog) item; blogId = blog.blogId; feedId = blog.feedId; } else { return; } ReaderActivityLauncher.showReaderBlogPreview(getActivity(), blogId, feedId); }

Target:
public void onBlogClicked(Object item) { if (item instanceof ReaderRecommendedBlog) { ReaderRecommendedBlog blog = (ReaderRecommendedBlog) item; ReaderActivityLauncher.showReaderBlogPreview(getActivity(), blog.blogId); } else if (item instanceof ReaderBlog) { ReaderBlog blog = (ReaderBlog) item; ReaderActivityLauncher.showReaderBlogOrFeedPreview(getActivity(), blog.blogId, blog.feedId); } }
Source:
public static void main(String... args) throws Exception { Options opts = new OptionsBuilder() .include( ".*" ) .warmupIterations( 20 ) .measurementIterations( 20 ) .jvmArgs( "-server" ) .jvmArgsAppend( "-XX:+UnlockCommercialFeatures", "-XX:+FlightRecorder" ) .forks( 1 ) .build(); new Runner(opts).run(); }

Target:
public static void main(String... args) throws Exception { String benchmarkArgsString = System.getProperty( BENCHMARK_VM_ARGS_KEY ); String[] benchMarkArgs; if ( benchmarkArgsString != null ) { benchMarkArgs = benchmarkArgsString.split( "\\s+" ); } else { benchMarkArgs = new String[0]; } Options opts = new OptionsBuilder() .include( ".*" ) .warmupIterations( 20 ) .measurementIterations( 20 ) .jvmArgs( "-server" ) .jvmArgsAppend( benchMarkArgs ) .forks( 1 ) .build(); new Runner(opts).run(); }
Source:
protected IntegrationNode(int nodeId, String name, Object nodeObject, Stats stats) { this.nodeId = nodeId; this.name = name; this.componentType = nodeObject instanceof NamedComponent ? ((NamedComponent) nodeObject).getComponentType() : nodeObject.getClass().getSimpleName(); this.stats = stats; if (nodeObject instanceof IntegrationObjectSupport) { String expressionString = ((IntegrationObjectSupport) nodeObject).getExpressionString(); if (expressionString != null) { this.properties.put("expression", expressionString); } } }

Target:
protected IntegrationNode(int nodeId, String name, Object nodeObject, Stats stats) { this.nodeId = nodeId; this.name = name; this.componentType = nodeObject instanceof NamedComponent ? ((NamedComponent) nodeObject).getComponentType() : nodeObject.getClass().getSimpleName(); this.stats = stats; if (nodeObject instanceof ExpressionCapable) { Expression expression = ((ExpressionCapable) nodeObject).getExpression(); if (expression != null) { this.properties.put("expression", expression.getExpressionString()); } } }
Source:
public void testSystemPropertiesOverrideConfigurationValues() { final String keyName = CoreConfig.MAX_CASSANDRA_CONNECTIONS.toString(); Configuration config = Configuration.getInstance(); try { Assert.assertEquals("75", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); System.setProperty(keyName, "something else"); Assert.assertEquals("something else", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); } finally { System.clearProperty(keyName); Configuration.clearProperty(keyName); } }

Target:
public void testSystemPropertiesOverrideConfigurationValues() { final String keyName = CoreConfig.MAX_CASSANDRA_CONNECTIONS.toString(); Configuration config = Configuration.getInstance(); try { Assert.assertEquals("75", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); System.setProperty(keyName, "something else"); Assert.assertEquals("something else", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); } finally { System.clearProperty(keyName); config.clearProperty(keyName); } }
Source:
public String[] getIndexNames() { return indexNames; }

Target:
public String[] getIndexNames() { return Arrays.copyOf(indexNames, indexNames.length); }
Source:
public Response getKafkaSourceSchema(@PathParam("topicName") String topicName) throws JsonProcessingException { try { LOG.info("Received path: [{}]", topicName); SchemaVersionInfo schemaVersionInfo = schemaRegistryClient.getLatestSchemaVersionInfo(topicName); String schema = schemaVersionInfo != null ? schemaVersionInfo.getSchemaText() : null; LOG.debug("######### Received schema from schema registry: ", schema); if (schema != null && !schema.isEmpty()) { schema = avroStreamsSchemaConverter.convertAvro(schema); } LOG.debug("######### Converted schema: ", schema); return WSUtils.respondEntity(schema, OK); } catch (SchemaNotFoundException e) { LOG.error("Schema not found for name: [{}]", topicName, e); throw EntityNotFoundException.byId(topicName); } catch (JsonProcessingException ex) { LOG.error("Error occurred while retrieving schema with name [{}]", topicName, ex); throw ex; } }

Target:
public Response getKafkaSourceSchema(@PathParam("topicName") String topicName) throws JsonProcessingException { try { LOG.info("Received path: [{}]", topicName); String schemaName = topicName + ":v"; SchemaVersionInfo schemaVersionInfo = schemaRegistryClient.getLatestSchemaVersionInfo(schemaName); String schema = schemaVersionInfo != null ? schemaVersionInfo.getSchemaText() : null; LOG.debug("######### Received schema from schema registry: ", schema); if (schema != null && !schema.isEmpty()) { schema = avroStreamsSchemaConverter.convertAvro(schema); } LOG.debug("######### Converted schema: ", schema); return WSUtils.respondEntity(schema, OK); } catch (SchemaNotFoundException e) { LOG.error("Schema not found for name: [{}]", topicName, e); throw EntityNotFoundException.byId(topicName); } catch (JsonProcessingException ex) { LOG.error("Error occurred while retrieving schema with name [{}]", topicName, ex); throw ex; } }
Source:
private String getFullLogMessage(MessageContext synCtx) { StringBuffer sb = new StringBuffer(); sb.append(getSimpleLogMessage(synCtx)); try { org.apache.axis2.context.MessageContext a2mc = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); if (JsonUtil.hasAJsonPayload(a2mc) && synCtx.getEnvelope() == null) { sb.append(separator).append("Payload: ").append(JsonUtil.jsonPayloadToString(a2mc)); } else if (synCtx.getEnvelope() != null) { sb.append(separator).append("Envelope: ").append(synCtx.getEnvelope()); } } catch (Exception e) { SOAPEnvelope envelope = synCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope() :OMAbstractFactory.getSOAP12Factory().getDefaultEnvelope(); try { synCtx.setEnvelope(envelope); } catch (Exception e1) { log.error("Could not replace faulty SOAP Envelop. Error: " + e1.getLocalizedMessage()); return sb.toString(); } handleException("Could not build full log message: " + e.getLocalizedMessage(), e, synCtx); } return trimLeadingSeparator(sb); }

Target:
private String getFullLogMessage(MessageContext synCtx) { StringBuffer sb = new StringBuffer(); sb.append(getSimpleLogMessage(synCtx)); try { org.apache.axis2.context.MessageContext a2mc = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); if (synCtx.getEnvelope() != null) { sb.append(separator).append("Envelope: ").append(synCtx.getEnvelope()); } else if (JsonUtil.hasAJsonPayload(a2mc)) { sb.append(separator).append("Payload: ").append(JsonUtil.jsonPayloadToString(a2mc)); } } catch (Exception e) { SOAPEnvelope envelope = synCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope() :OMAbstractFactory.getSOAP12Factory().getDefaultEnvelope(); try { synCtx.setEnvelope(envelope); } catch (Exception e1) { log.error("Could not replace faulty SOAP Envelop. Error: " + e1.getLocalizedMessage()); return sb.toString(); } handleException("Could not build full log message: " + e.getLocalizedMessage(), e, synCtx); } return trimLeadingSeparator(sb); }
Source:
KafkaSinkConfiguration(@JsonProperty(defaultValue=DEFAULT_TOPIC) final String topic, @JsonProperty final KafkaSinkMode mode) { this.topic = Optional.ofNullable(topic).orElse(DEFAULT_TOPIC); this.mode = Optional.ofNullable(mode).orElse(KafkaSinkMode.NAKED); }

Target:
KafkaSinkConfiguration(@JsonProperty(defaultValue=DEFAULT_TOPIC) final String topic, @JsonProperty final KafkaSinkMode mode) { this.topic = Optional.ofNullable(topic).orElse(DEFAULT_TOPIC); this.mode = Optional.ofNullable(mode).orElse(DEFAULT_SINK_MODE); }
Source:
private double estimateOutlierProbability(final AlleleFractionData data) { final UnivariateObjectiveFunction objective = new UnivariateObjectiveFunction(outlierProbability -> AlleleFractionModeller.logLikelihood(state.shallowCopyWithProposedOutlierProbability(outlierProbability), data)); final SearchInterval searchInterval = new SearchInterval(0.0, 0.1, state.outlierProbability()); return new BrentOptimizer(0.01, 0.001).optimize(objective, GoalType.MAXIMIZE, searchInterval, new MaxEval(1000)).getPoint(); }

Target:
private double estimateOutlierProbability(final AlleleFractionData data) { final UnivariateObjectiveFunction objective = new UnivariateObjectiveFunction(outlierProbability -> AlleleFractionModeller.logLikelihood(state.shallowCopyWithProposedOutlierProbability(outlierProbability), data)); final SearchInterval searchInterval = new SearchInterval(0.0, MAX_REASONABLE_OUTLIER_PROBABILITY, state.outlierProbability()); return OPTIMIZER.optimize(objective, GoalType.MAXIMIZE, searchInterval, BRENT_MAX_EVAL).getPoint(); }
Source:
private void installConnectionsToolbar() { toolbar_.removeAllWidgets(); newConnectionButton_ = toolbar_.addLeftWidget(commands_.newConnection().createToolbarButton()); toolbar_.addLeftSeparator(); toolbar_.addRightWidget(searchWidget_); setSecondaryToolbarVisible(false); }

Target:
private void installConnectionsToolbar() { toolbar_.removeAllWidgets(); toolbar_.addLeftWidget(commands_.newConnection().createToolbarButton()); toolbar_.addLeftSeparator(); toolbar_.addRightWidget(searchWidget_); setSecondaryToolbarVisible(false); }
Source:
public void testGetFileCounts() { Response response = utilizationService.getFileCounts(); Map<Long, Long> resultMap = (LinkedHashMap<Long, Long>) response.getEntity(); int totalBins = 16; assertEquals(totalBins, resultMap.size()); assertEquals(1L, (long) resultMap.get(1024L)); assertEquals(1L, (long) resultMap.get(10240L)); assertEquals(2L, (long) resultMap.get(10240000L)); assertEquals(0L, (long) resultMap.get(1024000L)); }

Target:
public void testGetFileCounts() { List<FileCountBySize> resultList = setUpResultList(); utilizationService = mock(UtilizationService.class); when(utilizationService.getFileCounts()).thenCallRealMethod(); when(utilizationService.getDao()).thenReturn(fileCountBySizeDao); when(fileCountBySizeDao.findAll()).thenReturn(resultList); Response response = utilizationService.getFileCounts(); List<FileCountBySize> responseList = (List<FileCountBySize>) response.getEntity(); verify(fileCountBySizeDao, times(1)).findAll(); assertEquals(maxBinSize, responseList.size()); assertEquals(resultList, responseList); }
Source:
public void reportIssueWithFlow(JavaCheck javaCheck, Tree syntaxNode, String message, Iterable<List<Location>> flows, @Nullable Integer cost) { if(sonarComponents == null) { return; } Iterable<List<Location>> reportedFlows; if (sonarComponents.isSQGreaterThan64()) { reportedFlows = flows; } else { reportedFlows = javaCheck instanceof SECheck ? Iterables.limit(flows, 1) : flows; } sonarComponents.reportIssue(createAnalyzerMessage(file, javaCheck, syntaxNode, null, message, reportedFlows, cost)); }

Target:
public void reportIssueWithFlow(JavaCheck javaCheck, Tree syntaxNode, String message, Iterable<List<Location>> flows, @Nullable Integer cost) { Iterable<List<Location>> reportedFlows; if (sonarComponents.isSQGreaterThan64()) { reportedFlows = flows; } else { reportedFlows = javaCheck instanceof SECheck ? Iterables.limit(flows, 1) : flows; } sonarComponents.reportIssue(createAnalyzerMessage(file, javaCheck, syntaxNode, null, message, reportedFlows, cost)); }
Source:
public Optional<TimeZoneHistory> updateTimeZone(long accountId, final String clientTimeZoneId, int clientTimeZoneOffsetMillis){ final long updatedAt = DateTime.now().getMillis(); DateTimeZone clientTimeZone = DateTimeZone.UTC; try{ clientTimeZone = DateTimeZone.forID(clientTimeZoneId); }catch (IllegalArgumentException ex){ LOGGER.warn("Unrecognized Timezone ID {}, proceeding to derive from offset millis", clientTimeZoneId); clientTimeZone = DateTimeZone.forOffsetMillis(clientTimeZoneOffsetMillis); } String timeZoneId = clientTimeZone.getID(); final Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(accountId))); item.put(UPDATED_AT_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(updatedAt))); item.put(TIMEZONE_NAME_ATTRIBUTE_NAME, new AttributeValue().withS(timeZoneId)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, item); final PutItemResult putItemResult = dynamoDBClient.putItem(putItemRequest); if(putItemResult != null){ LOGGER.debug("Update time zone for account: {}, offset: {}, id: {}", accountId, clientTimeZone.getOffset(DateTime.now().getMillis()), timeZoneId); return Optional.of(new TimeZoneHistory(updatedAt, clientTimeZone.getOffset(DateTime.now().getMillis()), timeZoneId)); } LOGGER.warn("Account update timezone failed, AWS error.", accountId); return Optional.absent(); }

Target:
public Optional<TimeZoneHistory> updateTimeZone(long accountId, final String clientTimeZoneId, int clientTimeZoneOffsetMillis){ final long updatedAt = DateTime.now().getMillis(); DateTimeZone clientTimeZone = DateTimeZone.UTC; try{ clientTimeZone = DateTimeZone.forID(clientTimeZoneId); }catch (IllegalArgumentException ex){ LOGGER.warn("Unrecognized Timezone ID from account {}, proceeding to derive from offset millis", clientTimeZoneId, accountId); clientTimeZone = DateTimeZone.forOffsetMillis(clientTimeZoneOffsetMillis); } String timeZoneId = clientTimeZone.getID(); final Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(accountId))); item.put(UPDATED_AT_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(updatedAt))); item.put(TIMEZONE_NAME_ATTRIBUTE_NAME, new AttributeValue().withS(timeZoneId)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, item); final PutItemResult putItemResult = dynamoDBClient.putItem(putItemRequest); if(putItemResult != null){ LOGGER.debug("Update time zone for account: {}, offset: {}, id: {}", accountId, clientTimeZone.getOffset(DateTime.now().getMillis()), timeZoneId); return Optional.of(new TimeZoneHistory(updatedAt, clientTimeZone.getOffset(DateTime.now().getMillis()), timeZoneId)); } LOGGER.warn("Account update timezone failed, AWS error.", accountId); return Optional.absent(); }
Source:
@Override protected Void run(String name) throws IgniteException { new SnapshotMXBeanImpl(ignite.context()).createSnapshot(name); return null; }

Target:
@Override protected String run(String name) throws IgniteException { new SnapshotMXBeanImpl(ignite.context()).createSnapshot(name); return "Snapshot operation started: " + name; }
Source:
public void openLevel(String mainUlCSSClasses) { openLevel(new TreeSet<String>(Arrays.asList(StringUtils.split(mainUlCSSClasses, ' ')))); }

Target:
public void openLevel(String mainUlCSSClasses) { openLevel(new LinkedHashSet<String>(Arrays.asList(StringUtils.split(mainUlCSSClasses, ' ')))); }
Source:
public boolean canPushMerges() { if (projectControl.controlForRef(getRefName()).canPerform( Permission.PUSH_MERGE) && canWrite()) { return true; } else if (projectControl.controlForRef( MagicBranch.NEW_CHANGE + getRefName()) .canPerform(Permission.PUSH_MERGE) && canWrite()) { return true; } return false; }

Target:
public boolean canPushMerges() { if (this.canPerform(Permission.PUSH_MERGE) && canWrite()) { return true; } else if (projectControl.controlForRef(MagicBranch.NEW_CHANGE + getRefName()) .canPerform(Permission.PUSH_MERGE) && canWrite()) { return true; } return false; }
Source:
public JsonNode toJson() { return toJson("requests","request"); }

Target:
public JsonNode toJson() { throw new UnsupportedOperationException(); }
Source:
protected void refreshFile(IFile file) throws CoreException { if (file == null) { return; } class RefreshFileOperation extends DocumentProviderOperation implements ISchedulingRuleProvider { @Override protected void execute(IProgressMonitor m) throws CoreException { refreshFile(file, m); } @Override public ISchedulingRule getSchedulingRule() { return fResourceRuleFactory.refreshRule(file); } } executeOperation(new RefreshFileOperation(), getProgressMonitor()); }

Target:
protected void refreshFile(IFile file) throws CoreException { refreshFile(file, getProgressMonitor()); }
Source:
public static IntervalList invert(final IntervalList list) { final IntervalList inverse = new IntervalList(list.header.clone()); final ListMap<Integer, Interval> map = new ListMap<>(); for (final Interval i : list.uniqued().getIntervals()) { final int sequenceIndex = list.getHeader().getSequenceIndex(i.getContig()); ValidationUtils.nonNull(sequenceIndex, () -> String.format("Cannot add interval %s, contig not in header", i.toString())); map.add(sequenceIndex, i); } int intervals = 0; for (final SAMSequenceRecord samSequenceRecord : list.getHeader().getSequenceDictionary().getSequences()) { final Integer sequenceIndex = samSequenceRecord.getSequenceIndex(); final String sequenceName = samSequenceRecord.getSequenceName(); final int sequenceLength = samSequenceRecord.getSequenceLength(); int lastCoveredPosition = 0; if (map.containsKey(sequenceIndex)) { for (final Interval i : map.get(sequenceIndex)) { if (i.getStart() > lastCoveredPosition + 1) { inverse.add(new Interval(sequenceName, lastCoveredPosition + 1, i.getStart() - 1, false, "interval-" + (++intervals))); } lastCoveredPosition = i.getEnd(); } } if (sequenceLength > lastCoveredPosition) { inverse.add(new Interval(sequenceName, lastCoveredPosition + 1, sequenceLength, false, "interval-" + (++intervals))); } } return inverse; }

Target:
public static IntervalList invert(final IntervalList list) { final IntervalList inverse = new IntervalList(list.header.clone()); final ListMap<Integer, Interval> map = new ListMap<>(); for (final Interval i : list.uniqued().getIntervals()) { final int sequenceIndex = list.getHeader().getSequenceIndex(i.getContig()); ValidationUtils.validateArg(sequenceIndex != SAMSequenceRecord.UNAVAILABLE_SEQUENCE_INDEX, () -> String.format("Cannot add interval %s, contig not in header", i.toString())); map.add(sequenceIndex, i); } int intervals = 0; for (final SAMSequenceRecord samSequenceRecord : list.getHeader().getSequenceDictionary().getSequences()) { final Integer sequenceIndex = samSequenceRecord.getSequenceIndex(); final String sequenceName = samSequenceRecord.getSequenceName(); final int sequenceLength = samSequenceRecord.getSequenceLength(); int lastCoveredPosition = 0; if (map.containsKey(sequenceIndex)) { for (final Interval i : map.get(sequenceIndex)) { if (i.getStart() > lastCoveredPosition + 1) { inverse.add(new Interval(sequenceName, lastCoveredPosition + 1, i.getStart() - 1, false, "interval-" + (++intervals))); } lastCoveredPosition = i.getEnd(); } } if (sequenceLength > lastCoveredPosition) { inverse.add(new Interval(sequenceName, lastCoveredPosition + 1, sequenceLength, false, "interval-" + (++intervals))); } } return inverse; }
Source:
public String apply(long value) { return this.apply(Long.valueOf(value)); }

Target:
public String apply(long value) { return this.apply((Long)value); }
Source:
public void testInit() throws Exception { ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService, mockSystemService); serviceBean.init(); verify(mBeanServer).registerMBean(serviceBean, objectName); }

Target:
public void testInit() throws Exception { ApplicationServiceBean serviceBean = newApplicationServiceBean(); serviceBean.init(); verify(mBeanServer).registerMBean(serviceBean, objectName); }
Source:
public void testPullNonExistingImage() throws Exception { try { dockerRule.getClient().pullImageCmd("xvxcv/foo") .exec(new PullImageResultCallback()) .awaitCompletion(30, TimeUnit.SECONDS); fail("An exception is expected."); } catch (NotFoundException | DockerClientException e) { } }

Target:
public void testPullNonExistingImage() throws Exception { if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient()) .isGreaterOrEqual(RemoteApiVersion.VERSION_1_26)) { exception.expect(NotFoundException.class); } else { exception.expect(DockerClientException.class); } dockerRule.getClient().pullImageCmd("xvxcv/foo") .exec(new PullImageResultCallback()) .awaitCompletion(30, TimeUnit.SECONDS); }
Source:
private static Engine.SpiAndProvider tryTransformWithProvider(InitParams initParams, String[] transformParts, NeedToSet type, Provider.Service service) throws InvalidKeyException, InvalidAlgorithmParameterException { try { if (!matchAttribute(service, ATTRIBUTE_MODES, transformParts[1]) || !matchAttribute(service, ATTRIBUTE_PADDINGS, transformParts[2])) { return null; } Engine.SpiAndProvider sap = ENGINE.getInstance(service, null); if (sap.spi == null || sap.provider == null) { return null; } if (!(sap.spi instanceof CipherSpi)) { return null; } CipherSpi spi = (CipherSpi) sap.spi; if (((type == NeedToSet.MODE) || (type == NeedToSet.BOTH)) && (transformParts[1] != null)) { spi.engineSetMode(transformParts[1]); } if (((type == NeedToSet.PADDING) || (type == NeedToSet.BOTH)) && (transformParts[2] != null)) { spi.engineSetPadding(transformParts[2]); } if (initParams != null) { switch (initParams.initType) { case ALGORITHM_PARAMS: spi.engineInit(initParams.opmode, initParams.key, initParams.params, initParams.random); break; case ALGORITHM_PARAM_SPEC: spi.engineInit(initParams.opmode, initParams.key, initParams.spec, initParams.random); break; case KEY: spi.engineInit(initParams.opmode, initParams.key, initParams.random); break; default: throw new AssertionError("This should never be reached"); } } return sap; } catch (NoSuchAlgorithmException ignored) { } catch (NoSuchPaddingException ignored) { } return null; }

Target:
private static Engine.SpiAndProvider tryTransformWithProvider(InitParams initParams, String[] transformParts, NeedToSet type, Provider.Service service) throws InvalidKeyException, InvalidAlgorithmParameterException { try { if (!matchAttribute(service, ATTRIBUTE_MODES, transformParts[1]) || !matchAttribute(service, ATTRIBUTE_PADDINGS, transformParts[2])) { return null; } Engine.SpiAndProvider sap = ENGINE.getInstance(service, null); if (sap.spi == null || sap.provider == null) { return null; } CipherSpi spi = (CipherSpi) sap.spi; if (((type == NeedToSet.MODE) || (type == NeedToSet.BOTH)) && (transformParts[1] != null)) { spi.engineSetMode(transformParts[1]); } if (((type == NeedToSet.PADDING) || (type == NeedToSet.BOTH)) && (transformParts[2] != null)) { spi.engineSetPadding(transformParts[2]); } if (initParams != null) { switch (initParams.initType) { case ALGORITHM_PARAMS: spi.engineInit(initParams.opmode, initParams.key, initParams.params, initParams.random); break; case ALGORITHM_PARAM_SPEC: spi.engineInit(initParams.opmode, initParams.key, initParams.spec, initParams.random); break; case KEY: spi.engineInit(initParams.opmode, initParams.key, initParams.random); break; default: throw new AssertionError("This should never be reached"); } } return sap; } catch (NoSuchAlgorithmException ignored) { } catch (NoSuchPaddingException ignored) { } return null; }
Source:
public MacPool getMacPoolForDataCenter(Guid dataCenterId, CommandContext commandContext) { final MacPool macPool; try { macPool = getMacPoolById(getMacPoolId(dataCenterId), commandContext); } catch (Exception e) { throw new IllegalStateException( String.format("An exception was thrown while retrieving the mac-pool for DC='%s'", dataCenterId), e); } return macPool; }

Target:
public MacPool getMacPoolForDataCenter(Guid dataCenterId, CommandContext commandContext) { try { return getMacPoolById(getMacPoolId(dataCenterId), commandContext); } catch (RuntimeException e) { throw new IllegalStateException( String.format("An exception was thrown while retrieving the mac-pool for DC='%s'", dataCenterId), e); } }
Source:
private PostUploadHookChain(List<PostUploadHook> hooks) { this.hooks = new ArrayList<>(hooks); }

Target:
private PostUploadHookChain(List<PostUploadHook> hooks) { this.hooks = Collections.unmodifiableList(hooks); }
Source:
public void init(LogFeederProps logFeederProperties) throws Exception { super.init(logFeederProperties); port = (int) ObjectUtils.defaultIfNull(((InputSocketDescriptor)getInputDescriptor()).getPort(), 0); if (port == 0) { throw new IllegalArgumentException(String.format("Port needs to be set for socket input (type: %s)", getInputDescriptor().getType())); } protocol = (String) ObjectUtils.defaultIfNull(((InputSocketDescriptor)getInputDescriptor()).getProtocol(), "tcp"); secure = (boolean) ObjectUtils.defaultIfNull(((InputSocketDescriptor)getInputDescriptor()).isSecure(), false); log4j = (boolean) ObjectUtils.defaultIfNull(((InputSocketDescriptor)getInputDescriptor()).isLog4j(), false); }

Target:
public void init(LogFeederProps logFeederProperties) throws Exception { super.init(logFeederProperties); port = (int) ObjectUtils.defaultIfNull(getInputDescriptor().getPort(), 0); if (port == 0) { throw new IllegalArgumentException(String.format("Port needs to be set for socket input (type: %s)", getInputDescriptor().getType())); } protocol = (String) ObjectUtils.defaultIfNull(getInputDescriptor().getProtocol(), "tcp"); secure = (boolean) ObjectUtils.defaultIfNull(getInputDescriptor().isSecure(), false); log4j = (boolean) ObjectUtils.defaultIfNull(getInputDescriptor().isLog4j(), false); }
Source:
public void ensureBucketExists() { List<Bucket> buckets = amazonS3.listBuckets(); Optional<Bucket> existingBucket = buckets.stream().filter(b -> b.getName().equals(bucket)).findFirst(); if (!existingBucket.isPresent()) { if (StringUtils.isNullOrEmpty(region)) { log.info("Creating bucket " + bucket + " in default region"); amazonS3.createBucket(bucket); } else { log.info("Creating bucket " + bucket + " in region " + region + "..."); amazonS3.createBucket(bucket, region); } } }

Target:
public void ensureBucketExists() { HeadBucketRequest request = new HeadBucketRequest(bucket); try { amazonS3.headBucket(request); } catch (AmazonServiceException e) { if (e.getStatusCode() == 404) { if (StringUtils.isNullOrEmpty(region)) { log.info("Creating bucket " + bucket + " in default region"); amazonS3.createBucket(bucket); } else { log.info("Creating bucket " + bucket + " in region " + region + "..."); amazonS3.createBucket(bucket, region); } } else { throw e; } } }
Source:
public void addFilter(ITmfFilterTreeNode filter) { ITmfFilterTreeNode root = fViewer.getInput(); for (int i = 0; i < root.getChildrenCount(); i++) { if (root.getChild(0).equals(filter)) { return; } } root.addChild(filter); fViewer.setInput(root); }

Target:
public void addFilter(ITmfFilterTreeNode filter) { ITmfFilterTreeNode root = fViewer.getInput(); for (int i = 0; i < root.getChildrenCount(); i++) { if (root.getChild(i).equals(filter)) { return; } } root.addChild(filter); fViewer.setInput(root); }
Source:
public static Integer getIntegerParamValue(String paramName, Configuration configuration) throws NumberFormatException { String paramValue = configuration.get(paramName); if (StringUtils.isNotBlank(paramValue) && !UNDEFINED_NONEMPTY_VALUE.equals(paramValue)) { return Integer.parseInt(paramValue); } else { return null; } }

Target:
public static Integer getIntegerParamValue(String paramName, Configuration configuration) throws NumberFormatException { String paramValue = getParamValue(paramName, configuration); return paramValue!=null?Integer.valueOf(paramValue):null; }
Source:
public void createServiceNoUser() throws Exception { CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = null; try { service = client.addService(serviceRepo, "iamnotarealuser", installationId); } catch (ApiException ex) { } assertNull("Should not be able to add service since the username does not exist on Dockstore.", service); }

Target:
public void createServiceNoUser() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; try { client.addService(serviceRepo, "iamnotarealuser", installationId); } catch (ApiException ex) { } final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be no matching service", 0, count); }
Source:
public void deleteLabel(String user, String labelId) throws APIManagementException { if (isAttachedLabel(user, labelId)) { APIUtil.handleException("Unable to delete label. Label is already attached to a API"); } apiMgtDAO.deleteLabel(labelId); }

Target:
public void deleteLabel(String user, String labelId) throws APIManagementException { if (isAttachedLabel(user, labelId)) { APIUtil.handleException("Unable to delete the label. It is attached to an API"); } apiMgtDAO.deleteLabel(labelId); }
Source:
public void shutdownShouldStopAllSolvers() { int[] problemIds = new int[Runtime.getRuntime().availableProcessors() * 3]; for (int i = 0; i < problemIds.length; i++) { problemIds[i] = i; } Arrays.stream(problemIds) .forEach(problemId -> { TestdataSolution problem = createTestProblem((long) problemId); solverManager.solve(problemId, problem, null, null); }); solverManager.shutdown(); Arrays.stream(problemIds) .forEach(problemId -> assertEquals(SolverStatus.TERMINATED_EARLY, solverManager.getSolverStatus(problemId))); }

Target:
public void shutdownShouldStopAllSolvers() throws InterruptedException { int problemCount = Runtime.getRuntime().availableProcessors() * 3; IntStream.range(0, problemCount) .forEach(problemId -> { TestdataSolution problem = createTestProblem((long) problemId); solverManager.solve(problemId, problem, null, null); }); solverManager.shutdown(); IntStream.range(0, problemCount) .forEach(problemId -> { assertFalse(solverManager.isProblemSubmitted(problemId)); }); }
Source:
private void add(byte[] bytes) { int[] hashes = createHashes(bytes); for (int hash : hashes) bitset.set(Math.abs(hash % bitSetSize), true); numberOfAddedElements ++; }

Target:
private void add(byte[] bytes) { int[] hashes = createHashes(bytes); for (int hash : hashes) { bitset.set(Math.abs(hash % bitSetSize), true); } numberOfAddedElements++; }
Source:
public void receiveRequest(final Exchange exchange, final Request request) { if (request.isDuplicate()) { Response currentResponse = exchange.getCurrentResponse(); if (currentResponse != null) { LOGGER.debug("respond with the current response to the duplicate request"); if (currentResponse.isConfirmable()) { exchange.setFailedTransmissionCount(1); EmptyMessage ack = EmptyMessage.newACK(request); sendEmptyMessage(exchange, ack); } lower().sendResponse(exchange, currentResponse); } else if (exchange.getCurrentRequest().isAcknowledged()) { LOGGER.debug("duplicate request was acknowledged but no response computed yet. Retransmit ACK"); EmptyMessage ack = EmptyMessage.newACK(request); sendEmptyMessage(exchange, ack); } else if (exchange.getCurrentRequest().isRejected()) { LOGGER.debug("duplicate request was rejected. Reject again"); EmptyMessage rst = EmptyMessage.newRST(request); sendEmptyMessage(exchange, rst); } else { LOGGER.debug("server has not yet decided what to do with the request. We ignore the duplicate."); } } else { exchange.setCurrentRequest(request); upper().receiveRequest(exchange, request); } }

Target:
public void receiveRequest(final Exchange exchange, final Request request) { if (request.isDuplicate()) { Response currentResponse = exchange.getCurrentResponse(); if (currentResponse != null) { if (currentResponse.getType() == Type.NON || currentResponse.getType() == Type.CON) { if (request.isConfirmable()) { EmptyMessage ack = EmptyMessage.newACK(request); sendEmptyMessage(exchange, ack); } if (currentResponse.isConfirmable()) { int failedCount; synchronized (exchange) { failedCount = exchange.getFailedTransmissionCount() + 1; exchange.setFailedTransmissionCount(failedCount); } LOGGER.debug("Request Duplicate: retransmit response, failed: {}, response: {}", new Object[] { failedCount, currentResponse }); currentResponse.retransmitting(); sendResponse(exchange, currentResponse); return; } } LOGGER.debug("respond with the current response to the duplicate request"); lower().sendResponse(exchange, currentResponse); } else if (exchange.getCurrentRequest().isAcknowledged()) { LOGGER.debug("duplicate request was acknowledged but no response computed yet. Retransmit ACK"); EmptyMessage ack = EmptyMessage.newACK(request); sendEmptyMessage(exchange, ack); } else if (exchange.getCurrentRequest().isRejected()) { LOGGER.debug("duplicate request was rejected. Reject again"); EmptyMessage rst = EmptyMessage.newRST(request); sendEmptyMessage(exchange, rst); } else { LOGGER.debug("server has not yet decided what to do with the request. We ignore the duplicate."); } } else { exchange.setCurrentRequest(request); upper().receiveRequest(exchange, request); } }
Source:
public List<LogEntry> getLogEntries() { return logEntries; }

Target:
public List<LogEntry> getLogEntries() { return Collections.unmodifiableList(logEntries); }
Source:
public CompletableFuture<?> updateIndex(Object key, Object value, int segment) { if (value == null || Thread.currentThread().isInterrupted()) { return CompletableFuture.completedFuture(null); } if (!getGlobalScope().getIncludedIndexedTypes().contains(value.getClass())) { return CompletableFuture.completedFuture(null); } PojoIndexer indexer = searchMappingHolder.getSearchMapping().getMappingSession().createIndexer(); final String idInString = keyTransformationHandler.keyToString(key, segment); return indexer.add(PojoRawTypeIdentifier.of(value.getClass()), idInString, value); }

Target:
public CompletableFuture<?> updateIndex(Object key, Object value, int segment) { if (value == null || Thread.currentThread().isInterrupted()) { return CompletableFuture.completedFuture(null); } final String idInString = keyTransformationHandler.keyToString(key, segment); return searchMappingHolder.getSearchMapping().getSearchIndexer().addOrUpdate(idInString, value); }
Source:
public RpslObject getAbuseContactRole(final RpslObject rpslObject) { if(!ripeSources.contains(rpslObject.getValueForAttribute(AttributeType.SOURCE))) { return null; } switch (rpslObject.getType()) { case INETNUM: case INET6NUM: final RpslObject role = getAbuseContactRoleInternal(rpslObject); if (role == null) { final RpslObject parentObject = getParentObject(rpslObject); if (parentObject != null && !isMaintainedByRs(rpslObject)) { return getAbuseContactRole(parentObject); } } return role; case AUT_NUM: return getAbuseContactRoleInternal(rpslObject); default: return null; } }

Target:
public RpslObject getAbuseContactRole(final RpslObject rpslObject) { if(!mainSources.contains(rpslObject.getValueForAttribute(AttributeType.SOURCE))) { return null; } switch (rpslObject.getType()) { case INETNUM: case INET6NUM: final RpslObject role = getAbuseContactRoleInternal(rpslObject); if (role == null) { final RpslObject parentObject = getParentObject(rpslObject); if (parentObject != null && !isMaintainedByRs(rpslObject)) { return getAbuseContactRole(parentObject); } } return role; case AUT_NUM: return getAbuseContactRoleInternal(rpslObject); default: return null; } }
Source:
protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (isIgnored(method)) { notifier.fireTestIgnored(description); } else { Object test = null; try { test = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); } catch (Throwable e) { e.printStackTrace(); } boolean skipped = false; if (test != null) { List<TestRule> testRules = getTestRules(test); for (TestRule testRule : testRules) { Class<? extends TestRule> klass = testRule.getClass(); klass.getCanonicalName(); if ("org.eclipse.mylyn.commons.sdk.util.ConditionalIgnoreRule" .equals(klass.getCanonicalName())) { Statement statement = testRule.apply(null, description); if (statement != null) { skipped = true; break; } } } } if (skipped) { notifier.fireTestIgnored(description); } else { runTest(methodBlock(method), description, notifier); } } }

Target:
protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (isIgnored(method)) { notifier.fireTestIgnored(description); } else { Object test = null; try { test = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); } catch (Throwable e) { StatusHandler.log(new Status(IStatus.ERROR, "org.eclipse.mylyn.commons.sdk.util", NLS.bind("TestClassRunnerForFixture: Testclass {0} has no public constructor", getTestClass().getName()), e)); return; } boolean skipped = false; if (test != null) { List<TestRule> testRules = getTestRules(test); for (TestRule testRule : testRules) { Class<? extends TestRule> klass = testRule.getClass(); klass.getCanonicalName(); if (klass == ConditionalIgnoreRule.class) { Statement statement = testRule.apply(null, description); if (statement != null) { skipped = true; break; } } } if (skipped) { notifier.fireTestIgnored(description); } else { runTest(methodBlock(method), description, notifier); } } } }
Source:
public void testClientNodeRestart() throws Exception { lazyAllocation = true; client = false; IgniteEx srv = startSrv()[0]; IgniteEx clnt = startClientGrid(2); createCacheAndPut(clnt); stopAllGrids(false); srv = startSrv()[0]; IgniteCache<Integer, String> cache = startClientGrid(2).cache("my-cache-2"); assertEquals("test", cache.get(1)); }

Target:
public void testClientNodeRestart() throws Exception { lazyAllocation = true; IgniteEx srv = startSrv()[0]; IgniteEx clnt = startClientGrid(2); createCacheAndPut(clnt); stopAllGrids(false); srv = startSrv()[0]; IgniteCache<Integer, String> cache = startClientGrid(2).cache("my-cache-2"); assertEquals("test", cache.get(1)); }