auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void upgradeForWrite(int stripeId, String nodeName) { requireNonNull(nodeName); if (stripeId < 1) { throw new IllegalArgumentException("Stripe ID should be greater than or equal to 1"); } if (nomadServer.getChangeApplicator() != null) { throw new IllegalStateException("Nomad is already upgraded"); } router.register(SettingNomadChange.class, new SettingNomadChangeProcessor(dynamicConfigService, configChangeHandlerManager, dynamicConfigListener)); router.register(NodeRemovalNomadChange.class, new NodeRemovalNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); router.register(NodeAdditionNomadChange.class, new NodeAdditionNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); router.register(ClusterActivationNomadChange.class, new ClusterActivationNomadChangeProcessor(stripeId, nodeName)); router.register(StripeAdditionNomadChange.class, new StripeAdditionNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); router.register(StripeRemovalNomadChange.class, new StripeRemovalNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); nomadServer.setChangeApplicator( new ConfigChangeApplicator(stripeId, nodeName, new MultiSettingNomadChangeProcessor(nomadPermissionChangeProcessor .then(new ApplicabilityNomadChangeProcessor(stripeId, nodeName, router))))); LOGGER.debug("Successfully completed upgradeForWrite procedure"); }

Target:
public void upgradeForWrite(int stripeId, String nodeName) { requireNonNull(nodeName); if (stripeId < 1) { throw new IllegalArgumentException("Stripe ID should be greater than or equal to 1"); } if (nomadServer.getChangeApplicator() != null) { throw new IllegalStateException("Nomad is already upgraded"); } router.register(SettingNomadChange.class, new SettingNomadChangeProcessor(dynamicConfigService, configChangeHandlerManager, dynamicConfigListener)); router.register(NodeRemovalNomadChange.class, new NodeRemovalNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); router.register(NodeAdditionNomadChange.class, new NodeAdditionNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); router.register(ClusterActivationNomadChange.class, new ClusterActivationNomadChangeProcessor(stripeId, nodeName)); router.register(StripeAdditionNomadChange.class, new StripeAdditionNomadChangeProcessor(dynamicConfigService, dynamicConfigListener, licenseService)); router.register(StripeRemovalNomadChange.class, new StripeRemovalNomadChangeProcessor(dynamicConfigService, dynamicConfigListener)); nomadServer.setChangeApplicator( new ConfigChangeApplicator(stripeId, nodeName, new MultiSettingNomadChangeProcessor(nomadPermissionChangeProcessor .then(new ApplicabilityNomadChangeProcessor(stripeId, nodeName, router))))); LOGGER.debug("Successfully completed upgradeForWrite procedure"); }
Source:
public Response lookup(@Context final HttpServletRequest request, @PathParam("objectType") RdapRequestType requestType, @PathParam("key") final String key) { LOGGER.info("Request: {}", RestServiceHelper.getRequestURI(request)); Set<ObjectType> whoisObjectTypes = requestType.getWhoisObjectTypes(key); switch (requestType) { case autnum: { String autnumKey = String.format("AS%s", key); rdapRequestValidator.validateAutnum(autnumKey); return lookupForAutNum(request, autnumKey); } case domain: { rdapRequestValidator.validateDomain(key); return lookupObject(request, whoisObjectTypes, key); } case ip: { rdapRequestValidator.validateIp(request.getRequestURI(), key); return lookupWithRedirectUrl(request, whoisObjectTypes, key); } case entity: { rdapRequestValidator.validateEntity(key); return lookupObject(request, whoisObjectTypes, key); } case nameserver: { throw rdapExceptionMapper.notFound("nameserver not found"); } default: { throw rdapExceptionMapper.badRequest("unknown type"); } } }

Target:
public Response lookup(@Context final HttpServletRequest request, @PathParam("objectType") RdapRequestType requestType, @PathParam("key") final String key) { LOGGER.info("Request: {}", RestServiceHelper.getRequestURI(request)); Set<ObjectType> whoisObjectTypes = requestType.getWhoisObjectTypes(key); switch (requestType) { case AUTNUM: { String autnumKey = String.format("AS%s", key); rdapRequestValidator.validateAutnum(autnumKey); return lookupForAutNum(request, autnumKey); } case DOMAIN: { rdapRequestValidator.validateDomain(key); return lookupObject(request, whoisObjectTypes, key); } case IP: { rdapRequestValidator.validateIp(request.getRequestURI(), key); return lookupWithRedirectUrl(request, whoisObjectTypes, key); } case ENTITY: { rdapRequestValidator.validateEntity(key); return lookupObject(request, whoisObjectTypes, key); } case NAMESERVER: { throw new NotFoundException("nameserver not found"); } default: { throw new BadRequestException("unknown type"); } } }
Source:
public void testWithSqlObjectSingleValue() throws Exception { Dao dao = h2.getJdbi().onDemand(Dao.class); dao.insert(new Something(1, "Coda")); dao.insert(new Something(2, "Brian")); Optional<String> rs = dao.findNameById(1); assertThat(rs).isEqualTo(Optional.of("Coda")); rs = dao.smartFindNameById(1); assertThat(rs).isEqualTo(Optional.of("Coda")); rs = dao.inheritedGenericFindNameById(1); assertThat(rs).isEqualTo(Optional.of("Coda")); }

Target:
public void testWithSqlObjectSingleValue() throws Exception { Dao dao = h2.getJdbi().onDemand(Dao.class); dao.insert(new Something(1, "Coda")); dao.insert(new Something(2, "Brian")); Optional<String> rs = dao.findNameById(1); assertThat(rs).contains("Coda"); rs = dao.smartFindNameById(1); assertThat(rs).contains("Coda"); rs = dao.inheritedGenericFindNameById(1); assertThat(rs).contains("Coda"); }
Source:
public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException("This implementation only allows a one to one prefix to namespace ration."); }

Target:
public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException("This implementation only allows a one to one prefix to namespace ratio."); }
Source:
public void testCustomPartitionCountDoesNotOverridePartitioningIfSmaller() throws Exception { byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); KafkaTestBinder binder = getBinder(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); KafkaProducerProperties producerProperties = new KafkaProducerProperties(); producerProperties.setPartitionCount(5); producerProperties.setPartitionKeyExpression("payload"); KafkaConsumerProperties consumerProperties = new KafkaConsumerProperties(); consumerProperties.setMinPartitionCount(3); long uniqueBindingId = System.currentTimeMillis(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo" + uniqueBindingId + ".0", null, moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload).build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); Collection<Partition> partitions = binder.getCoreBinder().getConnectionFactory().getPartitions( "foo" + uniqueBindingId + ".0"); assertThat(partitions, hasSize(5)); producerBinding.unbind(); consumerBinding.unbind(); }

Target:
public void testCustomPartitionCountDoesNotOverridePartitioningIfSmaller() throws Exception { byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); KafkaTestBinder binder = getBinder(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); KafkaProducerProperties producerProperties = new KafkaProducerProperties(); producerProperties.setPartitionCount(5); producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("payload")); KafkaConsumerProperties consumerProperties = new KafkaConsumerProperties(); consumerProperties.setMinPartitionCount(3); long uniqueBindingId = System.currentTimeMillis(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo" + uniqueBindingId + ".0", null, moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload).build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); Collection<Partition> partitions = binder.getCoreBinder().getConnectionFactory().getPartitions( "foo" + uniqueBindingId + ".0"); assertThat(partitions, hasSize(5)); producerBinding.unbind(); consumerBinding.unbind(); }
Source:
protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (getVdsGroup() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); return false; } if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); final VM vm = getVm(); if (vm.getInterfaces().size() > getMacPoolForVm().getAvailableMacsCount()) { addCanDoActionMessage(VdcBllMessages.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); return false; } } return canDoActionAfterCloneVm(domainsMap); }

Target:
protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (getVdsGroup() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); return false; } if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); if (getVm().getInterfaces().size() > getMacPool().getAvailableMacsCount()) { addCanDoActionMessage(VdcBllMessages.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); return false; } } return canDoActionAfterCloneVm(domainsMap); }
Source:
private void createDestinationBondDefinitionsAndCopyAttachments() { Map<String, Bond> sourceBondsByName = sourceMapper.calcBondsByName(); Map<String, Bond> destinationBondsByName = destinationMapper.calcBondsByName(); for (Map.Entry<String, List<String>> bondEntry : destinationBondSlavesByName.entrySet()) { String bondName = bondEntry.getKey(); Bond sourceBond = sourceBondsByName.get(bondName); CreateOrUpdateBond createOrUpdateBond = createBond(bondName, bondEntry.getValue(), sourceBond.getBondOptions()); if (destinationBondsByName.containsKey(bondName)) { Bond destinationBond = destinationBondsByName.get(bondName); Guid bondId = destinationBond.getId(); bondsToRemove.remove(bondId); if (destinationBond.getIsManagement()) { List<String> bondNames = new ArrayList<>(destinationBondSlavesByName.keySet()); createOrUpdateBond.setName(findNextAvailableBondName(bondNames)); } else { createOrUpdateBond.setId(bondId); } } bondsToApply.add(createOrUpdateBond); attachmentsToApply.addAll(copyRelevantPartsFromNetworkAttachmentsAndModify(sourceBond.getId(), createOrUpdateBond.getName())); } }

Target:
private void createDestinationBondDefinitionsAndCopyAttachments() { for (Map.Entry<String, List<String>> bondEntry : destinationBondSlavesByName.entrySet()) { String bondName = bondEntry.getKey(); Bond sourceBond = sourceMapper.getBondByName(bondName); CreateOrUpdateBond createOrUpdateBond = createBond(bondName, bondEntry.getValue(), sourceBond.getBondOptions()); Bond destinationBond = destinationMapper.getBondByName(bondName); if (destinationBond != null) { Guid bondId = destinationBond.getId(); bondsToRemove.remove(bondId); if (destinationBond.getIsManagement()) { List<String> bondNames = new ArrayList<>(destinationBondSlavesByName.keySet()); createOrUpdateBond.setName(findNextAvailableBondName(bondNames)); } else { createOrUpdateBond.setId(bondId); } } bondsToApply.add(createOrUpdateBond); attachmentsToApply.addAll(copyRelevantPartsFromNetworkAttachmentsAndModify(sourceBond.getId(), createOrUpdateBond.getName())); } }
Source:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); stops = route.getStops(); int currentPosition = predictionViewPager.getCurrentItem(); int realPosition = stopViewPagerAdapter.getRealPosition(currentPosition); stopViewPagerAdapter.updatePredictions(realPosition, stops.get(realPosition).getPredictions()); int previousPosition = realPosition - 1; if (previousPosition == -1) { previousPosition = stops.size(); } stopViewPagerAdapter.updatePredictions(previousPosition, stops.get(previousPosition).getPredictions()); int nextPosition = realPosition + 1; if (nextPosition >= stops.size()) { nextPosition = 0; } stopViewPagerAdapter.updatePredictions(nextPosition, stops.get(nextPosition).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }

Target:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); stops = route.getStops(); int currentPosition = predictionViewPager.getCurrentItem(); int realPosition = stopViewPagerAdapter.getRealPosition(currentPosition); stopViewPagerAdapter.updatePredictions(realPosition, stops.get(realPosition).getPredictions()); int previousPosition = (realPosition - 1) % stops.size(); if (previousPosition < 0) { previousPosition += stops.size(); } stopViewPagerAdapter.updatePredictions(previousPosition, stops.get(previousPosition).getPredictions()); int nextPosition = (realPosition + 1) % stops.size(); stopViewPagerAdapter.updatePredictions(nextPosition, stops.get(nextPosition).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }
Source:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }

Target:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { if (!EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier())) return false; } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }
Source:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { ConnectorTableMetadata existingTable = tables.putIfAbsent(tableMetadata.getTable(), tableMetadata); if (existingTable != null && !ignoreExisting) { throw new IllegalArgumentException(format("Table %s already exists", tableMetadata.getTable())); } }

Target:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { ConnectorTableMetadata existingTable = tables.putIfAbsent(tableMetadata.getTable(), tableMetadata); if (existingTable != null && !ignoreExisting) { throw new IllegalArgumentException("Target table already exists: " + tableMetadata.getTable()); } }
Source:
public final Method setAccessible() { try { AccessPermissionChecker.checkAccessPermission(cachedMethod); } catch (AccessControlException ex) { throw new IllegalArgumentException("Illegal access to method" + cachedMethod.getName()); } return cachedMethod; }

Target:
public final Method setAccessible() { AccessPermissionChecker.checkAccessPermission(cachedMethod); return cachedMethod; }
Source:
private byte[] deserialize(NamedKey key, byte[] bytes) { final byte[] data = transcoder.decompress(bytes); final ByteBuffer buf = ByteBuffer.wrap(data); final int keyLength = buf.getInt(); final byte[] keyBytes = new byte[keyLength]; buf.get(keyBytes); final byte[] value = new byte[buf.remaining()]; buf.get(value); Preconditions.checkState(Arrays.equals(keyBytes, key.toByteArray()), "Keys do not match, possible hash collision?"); return value; }

Target:
private byte[] deserialize(NamedKey key, byte[] bytes) { final byte[] data = transcoder.decompress(bytes); return CacheImplUtils.deserializeValue(key, data); }
Source:
private void addParentLinksRecursive(Process child, LinkedList<DefaultTreeNode> result) { Process parent = child.getParent(); if (Objects.nonNull(parent)) { URI uri = ServiceManager.getProcessService().getMetadataFileUri(parent); DefaultTreeNode tree = new DefaultTreeNode(); tree.setExpanded(true); try { List<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive( ServiceManager.getMetsService().loadWorkpiece(uri).getRootElement(), child.getId()); DefaultTreeNode parentNode = tree; if (Objects.isNull(includedStructuralElementList)) { new DefaultTreeNode(new StructureTreeNode(this, parent.getTitle(), true, true, parent), tree); } else { for (IncludedStructuralElement includedStructuralElement : includedStructuralElementList) { StructuralElementViewInterface structuralElementView = dataEditor.getRuleset() .getStructuralElementView(includedStructuralElement.getType(), dataEditor.getAcquisitionStage(), dataEditor.getPriorityList()); parentNode = new DefaultTreeNode( new StructureTreeNode(this, structuralElementView.getLabel(), false, true, null), parentNode); parentNode.setExpanded(true); } } } catch (IOException e) { Helper.setErrorMessage("metadataReadError", e.getMessage(), logger, e); new DefaultTreeNode(new StructureTreeNode(this, parent.getTitle(), true, true, parent), tree); } result.addFirst(tree); addParentLinksRecursive(parent, result); } }

Target:
private void addParentLinksRecursive(Process child, LinkedList<DefaultTreeNode> result) { Process parent = child.getParent(); if (Objects.isNull(parent)) { return; } URI uri = ServiceManager.getProcessService().getMetadataFileUri(parent); DefaultTreeNode tree = new DefaultTreeNode(); tree.setExpanded(true); try { IncludedStructuralElement rootElement = ServiceManager.getMetsService().loadWorkpiece(uri).getRootElement(); List<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive(rootElement, child.getId()); DefaultTreeNode parentNode = tree; if (includedStructuralElementList.isEmpty()) { addTreeNode(parent.getTitle(), true, true, parent, tree); } else { for (IncludedStructuralElement includedStructuralElement : includedStructuralElementList) { parentNode = addTreeNode(includedStructuralElement.getType(), true, null, parentNode); } } } catch (IOException e) { Helper.setErrorMessage("metadataReadError", e.getMessage(), logger, e); addTreeNode(parent.getTitle(), true, true, parent, tree); } result.addFirst(tree); addParentLinksRecursive(parent, result); }
Source:
public Surface<Double, Double, DoubleMatrix1D> getParameterSensitivitySurface(final DoubleMatrix1D modelParameters) { final BasisFunctionAggregation<double[]> bSpline = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, DoubleMatrix1D> func = new Function2D<Double, DoubleMatrix1D>() { @Override public DoubleMatrix1D evaluate(final Double t, final Double k) { return bSpline.weightSensitivity(new double[] {t, k }); } }; return new FunctionalSurface<>(func); }

Target:
public Surface<Double, Double, DoubleMatrix1D> getParameterSensitivitySurface(final DoubleMatrix1D modelParameters) { ArgumentChecker.notNull(modelParameters, "modelParameters"); final BasisFunctionAggregation<double[]> bSpline = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, DoubleMatrix1D> func = new Function2D<Double, DoubleMatrix1D>() { @Override public DoubleMatrix1D evaluate(final Double t, final Double k) { return bSpline.weightSensitivity(new double[] {t, k }); } }; return new FunctionalSurface<>(func); }
Source:
public static String invertSortKey(String sk) { if (sk.equalsIgnoreCase("z")) { return "/"; } StringBuilder inv = new StringBuilder(16); inv.setLength(16); formatHexLong(inv, -1l - parseUnsignedHex(sk)); return inv.toString(); }

Target:
public static String invertSortKey(String sk) { if (sk.equalsIgnoreCase("z")) { return "/"; } else if (sk.equalsIgnoreCase("/")) { return "z"; } StringBuilder inv = new StringBuilder(16); inv.setLength(16); formatHexLong(inv, -1l - parseUnsignedHex(sk)); return inv.toString(); }
Source:
private void approveOne(final PatchSet.Id patchSetId) throws NoSuchChangeException, OrmException, EmailException, Failure { final Change.Id changeId = patchSetId.getParentKey(); if (changeComment == null) { changeComment = ""; } Set<ApprovalCategoryValue.Id> aps = new HashSet<ApprovalCategoryValue.Id>(); for (ApproveOption ao : optionList) { Short v = ao.value(); if (v != null) { aps.add(new ApprovalCategoryValue.Id(ao.getCategoryId(), v)); } } try { publishCommentsFactory.create(patchSetId, changeComment, aps, forceMessage).call(); if (abandonChange) { final ReviewResult result = abandonChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } else if (restoreChange) { final ReviewResult result = restoreChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } if (submitChange) { final ReviewResult result = submitFactory.create(patchSetId).call(); handleReviewResultErrors(result); } } catch (InvalidChangeOperationException e) { throw error(e.getMessage()); } catch (IllegalStateException e) { throw error(e.getMessage()); } if (publishPatchSet) { final ReviewResult result = publishDraftFactory.create(patchSetId).call(); handleReviewResultErrors(result); } else if (deleteDraftPatchSet) { final ReviewResult result = deleteDraftPatchSetFactory.create(patchSetId).call(); handleReviewResultErrors(result); } }

Target:
private void approveOne(final PatchSet.Id patchSetId) throws NoSuchChangeException, OrmException, EmailException, Failure { if (changeComment == null) { changeComment = ""; } Set<ApprovalCategoryValue.Id> aps = new HashSet<ApprovalCategoryValue.Id>(); for (ApproveOption ao : optionList) { Short v = ao.value(); if (v != null) { aps.add(new ApprovalCategoryValue.Id(ao.getCategoryId(), v)); } } try { publishCommentsFactory.create(patchSetId, changeComment, aps, forceMessage).call(); if (abandonChange) { final ReviewResult result = abandonChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } else if (restoreChange) { final ReviewResult result = restoreChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } if (submitChange) { final ReviewResult result = submitFactory.create(patchSetId).call(); handleReviewResultErrors(result); } } catch (InvalidChangeOperationException e) { throw error(e.getMessage()); } catch (IllegalStateException e) { throw error(e.getMessage()); } if (publishPatchSet) { final ReviewResult result = publishDraftFactory.create(patchSetId).call(); handleReviewResultErrors(result); } else if (deleteDraftPatchSet) { final ReviewResult result = deleteDraftPatchSetFactory.create(patchSetId).call(); handleReviewResultErrors(result); } }
Source:
private void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; } HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } response.setStatusCode(OK); return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } URI requestURI = request.getRequestURI(); StringBuilder sb = new StringBuilder(); String scheme = requestURI.getScheme(); sb.append(scheme); sb.append("://"); sb.append(requestURI.getHost()); int port = requestURI.getPort(); if (appendPort(scheme, port)) { sb.append(':').append(port); } sb.append(contextPath); sb.append(page); sendRedirect(response, sb.toString()); }

Target:
private void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; } HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } URI requestURI = request.getRequestURI(); StringBuilder sb = new StringBuilder(); String scheme = requestURI.getScheme(); sb.append(scheme); sb.append("://"); sb.append(requestURI.getHost()); int port = requestURI.getPort(); if (appendPort(scheme, port)) { sb.append(':').append(port); } sb.append(contextPath); sb.append(page); sendRedirect(response, sb.toString()); }
Source:
public Image imageFor(Entity entity, int facing, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { System.err.println("Unable to load image for entity: " + entity.getShortNameRaw()); return getGenericImage(entity, -1, mechTileset); } return entityImage.getFacing(facing); }

Target:
public Image imageFor(Entity entity, int facing, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { DefaultMmLogger.getInstance().error(getClass(), "imageFor()", "Unable to load image for entity: " + entity.getShortNameRaw()); return getGenericImage(entity, -1, mechTileset); } return entityImage.getFacing(facing); }
Source:
public static List<PostAggregator> prepareAggregations( List<String> otherOutputNames, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); final Map<String, AggregatorFactory> aggsFactoryMap = Maps.newHashMap(); for (AggregatorFactory aggFactory : aggFactories) { Preconditions.checkArgument(!aggsFactoryMap.containsKey(aggFactory.getName()), "[%s] already defined", aggFactory.getName()); aggsFactoryMap.put(aggFactory.getName(), aggFactory); } if (postAggs != null && !postAggs.isEmpty()) { final Set<String> combinedOutputNames = Sets.newHashSet(aggsFactoryMap.keySet()); combinedOutputNames.addAll(otherOutputNames); List<PostAggregator> decorated = Lists.newArrayListWithExpectedSize(postAggs.size()); for (final PostAggregator postAgg : postAggs) { final Set<String> dependencies = postAgg.getDependentFields(); final Set<String> missing = Sets.difference(dependencies, combinedOutputNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); Preconditions.checkArgument(combinedOutputNames.add(postAgg.getName()), "[%s] already defined", postAgg.getName()); decorated.add(postAgg.decorate(aggsFactoryMap)); } return decorated; } return postAggs; }

Target:
public static List<PostAggregator> prepareAggregations( List<String> otherOutputNames, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(otherOutputNames, "otherOutputNames cannot be null"); Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); final Set<String> combinedOutputNames = new HashSet<>(); combinedOutputNames.addAll(otherOutputNames); final Map<String, AggregatorFactory> aggsFactoryMap = new HashMap<>(); for (AggregatorFactory aggFactory : aggFactories) { Preconditions.checkArgument( combinedOutputNames.add(aggFactory.getName()), "[%s] already defined", aggFactory.getName() ); aggsFactoryMap.put(aggFactory.getName(), aggFactory); } if (postAggs != null && !postAggs.isEmpty()) { List<PostAggregator> decorated = Lists.newArrayListWithExpectedSize(postAggs.size()); for (final PostAggregator postAgg : postAggs) { final Set<String> dependencies = postAgg.getDependentFields(); final Set<String> missing = Sets.difference(dependencies, combinedOutputNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); Preconditions.checkArgument( combinedOutputNames.add(postAgg.getName()), "[%s] already defined", postAgg.getName() ); decorated.add(postAgg.decorate(aggsFactoryMap)); } return decorated; } return postAggs; }
Source:
public boolean equals(Object obj) { return HttpServerModule.class.equals(obj.getClass()); }

Target:
public boolean equals(Object obj) { return getClass().equals(obj.getClass()); }
Source:
public void testGroupExistence() throws Exception { UsersInitServlet servlet = new UsersInitServlet(); servlet.doGet(context.request(), context.response()); LOG.info(context.response().getOutputAsString()); JsonObject json = new JsonParser().parse(context.response().getOutputAsString()).getAsJsonObject(); JsonObject options = json.get("options").getAsJsonObject(); JsonArray groups = options.get("groups").getAsJsonArray(); assertEquals(2,groups.size()); JSONAssert.assertEquals("[allusers, users]", groups.toString(),false); }

Target:
public void testGroupExistence() throws Exception { UsersInitServlet servlet = new UsersInitServlet(); servlet.doGet(context.request(), context.response()); JsonObject json = new JsonParser().parse(context.response().getOutputAsString()).getAsJsonObject(); JsonObject options = json.get("options").getAsJsonObject(); JsonArray groups = options.get("groups").getAsJsonArray(); assertEquals(2,groups.size()); JSONAssert.assertEquals("[allusers, users]", groups.toString(),false); }
Source:
private List<Branch> getCommitBranches(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); for (int i = 0; i < branches.size(); i++) { branchList.add(createDto(Branch.class).withName(branches.get(i).getName())); } return branchList; }

Target:
private List<Branch> getCommitBranches(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); branches.forEach(ref->branchList.add(createDto(Branch.class).withName(ref.getName()))); return branchList; }
Source:
@Override public Expression implement(RexToLixTranslator translator, Expression inputEnumerable, RexCall call, PhysType inputPhysType, PhysType outputPhysType) { Expression intervalExpression = translator.translate(call.getOperands().get(2)); Expression intervalExpression2 = translator.translate(call.getOperands().get(3)); RexCall descriptor = (RexCall) call.getOperands().get(1); List<Expression> translatedOperands = new ArrayList<>(); Expression wmColIndexExpr = Expressions.constant(((RexInputRef) descriptor.getOperands().get(0)).getIndex()); translatedOperands.add(wmColIndexExpr); translatedOperands.add(intervalExpression); translatedOperands.add(intervalExpression2); return Expressions.call( BuiltInMethod.HOPPING.method, Expressions.list( Expressions.call(inputEnumerable, BuiltInMethod.ENUMERABLE_ENUMERATOR.method), translatedOperands.get(0), translatedOperands.get(1), translatedOperands.get(2))); }

Target:
@Override public Expression implement(RexToLixTranslator translator, Expression inputEnumerable, RexCall call, PhysType inputPhysType, PhysType outputPhysType) { Expression slidingInterval = translator.translate(call.getOperands().get(1)); Expression windowSize = translator.translate(call.getOperands().get(2)); RexCall descriptor = (RexCall) call.getOperands().get(0); List<Expression> translatedOperands = new ArrayList<>(); Expression wmColIndexExpr = Expressions.constant(((RexInputRef) descriptor.getOperands().get(0)).getIndex()); translatedOperands.add(wmColIndexExpr); translatedOperands.add(slidingInterval); translatedOperands.add(windowSize); return Expressions.call( BuiltInMethod.HOPPING.method, Expressions.list( Expressions.call(inputEnumerable, BuiltInMethod.ENUMERABLE_ENUMERATOR.method), translatedOperands.get(0), translatedOperands.get(1), translatedOperands.get(2))); }
Source:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); double temp; temp = loc.getBlock().getTemperature(); return new CDouble(temp, target); }

Target:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); return new CDouble(loc.getBlock().getTemperature(), target); }
Source:
public void testListProperty() { testWithAllMappers(new Runnable() { @Override public void run() { TestModel model = new TestModel(); List<String> numbers = Arrays.asList("0", "1", "2", "3"); model.setSomeList(numbers); database.persist(model); model = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertEquals(numbers, model.getSomeList()); assertEquals(numbers, model.getSomeList()); } }); }

Target:
public void testListProperty() { testWithAllMappers(new Runnable() { @Override public void run() { TestModel model = new TestModel(); List<String> numbers = Arrays.asList("0", "1", "2", "3"); model.setSomeList(numbers); database.persist(model); model = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); int currentFromJSONCount = currentMapper.fromJSONCount; assertFalse(model.hasTransitory(transitoryKeyForProperty(TestModel.SOME_LIST))); assertEquals(numbers, model.getSomeList()); assertEquals(currentFromJSONCount + 1, currentMapper.fromJSONCount); assertTrue(model.hasTransitory(transitoryKeyForProperty(TestModel.SOME_LIST))); assertEquals(numbers, model.getSomeList()); assertEquals(currentFromJSONCount + 1, currentMapper.fromJSONCount); } }); }
Source:
public void addStorage( IAEItemStack option ) { if( this.isStackNull( option ) ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.incStackSize( option.getStackSize() ); return; } final IAEItemStack opt = (IAEItemStack) option.copy(); this.putItemRecord( opt ); }

Target:
public void addStorage( IAEItemStack option ) { if( option == null ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.incStackSize( option.getStackSize() ); return; } final IAEItemStack opt = option.copy(); this.putItemRecord( opt ); }
Source:
public void githubProfileScraperOrgTest() { String profile = "fossasia"; String shortDescription = "Open Technologies in Asia"; String userName = "fossasia"; String userId = "6295529"; String location = "Singapore"; String specialLink = " <LINK_0>"; SusiThought response = GithubProfileScraper.scrapeGithub(profile); JSONObject fetchedProfile = (JSONObject)response.getData().get(0); assertTrue(fetchedProfile.has("short_description")); assertThat(fetchedProfile.getString("short_description"), is(shortDescription)); assertTrue(fetchedProfile.has("user_name")); assertThat(fetchedProfile.getString("user_name"), is(userName)); assertTrue(fetchedProfile.has("user_id")); assertThat(fetchedProfile.getString("user_id"), is(userId)); assertTrue(fetchedProfile.has("location")); assertThat(fetchedProfile.getString("location"), is(location)); assertTrue(fetchedProfile.has("special_link")); }

Target:
public void githubProfileScraperOrgTest() { String profile = "fossasia"; String shortDescription = "Open Technologies in Asia"; String userName = "fossasia"; String userId = "6295529"; String location = "Singapore"; String specialLink = "<LINK_0>"; SusiThought response = GithubProfileScraper.scrapeGithub(profile); JSONObject fetchedProfile = (JSONObject)response.getData().get(0); assertEquals(fetchedProfile.getString("short_description"), shortDescription); assertEquals(fetchedProfile.getString("user_name"), userName); assertEquals(fetchedProfile.getString("user_id"), userId); assertEquals(fetchedProfile.getString("location"), location); assertEquals(fetchedProfile.getString("special_link"), specialLink); }
Source:
public KeyStore getTrustStore() throws Exception{ if(tenantId != MultitenantConstants.SUPER_TENANT_ID) throw new CarbonException("Permission denied for accessing trust store"); KeyStore trustStore = null; ServerConfiguration serverConfiguration = ServerConfiguration.getInstance(); String file = new File(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE)); String password = serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_PASSWORD); FileInputStream in = null; try { in = new FileInputStream(file); store.load(in, password.toCharArray()); trustStore = store; } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } } return trustStore; }

Target:
public KeyStore getTrustStore() throws Exception { if(tenantId != MultitenantConstants.SUPER_TENANT_ID) throw new CarbonException("Permission denied for accessing trust store"); KeyStore trustStore = null; ServerConfiguration serverConfiguration = ServerConfiguration.getInstance(); String file = new File(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE)); String password = serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_PASSWORD); FileInputStream in = null; try { in = new FileInputStream(file); store.load(in, password.toCharArray()); trustStore = store; } catch (Exception e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw e; } } } return trustStore; }
Source:
public HiveMetastoreClient createMetastoreClient() { List<HostAndPort> metastores = new ArrayList<>(addresses); Collections.shuffle(metastores.subList(1, metastores.size())); TException lastException = null; for (HostAndPort metastore : metastores) { try { HiveMetastoreClient hiveMetastoreClient = clientFactory.create(metastore); if (!isNullOrEmpty(hiveUserName)) { hiveMetastoreClient.setUGI(hiveUserName, new ArrayList<String>()); } return hiveMetastoreClient; } catch (TException e) { lastException = e; } } if (!isNullOrEmpty(hiveUserName)) { throw new PrestoException(HIVE_METASTORE_ERROR, format("Failed connecting to Hive metastore: %s , HiveUserName is %s ", addresses, hiveUserName), lastException); } throw new PrestoException(HIVE_METASTORE_ERROR, "Failed connecting to Hive metastore: " + addresses, lastException); }

Target:
public HiveMetastoreClient createMetastoreClient() { List<HostAndPort> metastores = new ArrayList<>(addresses); Collections.shuffle(metastores.subList(1, metastores.size())); TException lastException = null; for (HostAndPort metastore : metastores) { try { HiveMetastoreClient hiveMetastoreClient = clientFactory.create(metastore); if (!isNullOrEmpty(metastoreUsername)) { hiveMetastoreClient.setUGI(metastoreUsername); } return hiveMetastoreClient; } catch (TException e) { lastException = e; } } throw new PrestoException(HIVE_METASTORE_ERROR, "Failed connecting to Hive metastore: " + addresses, lastException); }
Source:
public RHSHistory getHistory(String lhs) { MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs); if (rhsCache != null) { int count= rhsCache.size(); LinkedHashMap history= new LinkedHashMap((int) (count / 0.75)); int rank= 1; for (Iterator it= rhsCache.iterator(); it.hasNext(); rank++) { String type= (String) it.next(); history.put(type, Integer.valueOf(rank)); } return new RHSHistory(history); } return EMPTY_HISTORY; }

Target:
public RHSHistory getHistory(String lhs) { MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs); if (rhsCache != null) { int count= rhsCache.size(); LinkedHashMap history= new LinkedHashMap((int) (count / 0.75)); int rank= 1; for (Iterator it= rhsCache.iterator(); it.hasNext(); rank++) { String type= (String) it.next(); history.put(type, rank); } return new RHSHistory(history); } return EMPTY_HISTORY; }
Source:
public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); final Version appLatestVersion; { final String appLatestVersionString = response.header(HEADER_APP_LATEST_VERSION); if (appLatestVersionString == null) { appLatestVersion = null; } else { try { appLatestVersion = new Version(appLatestVersionString); } catch (ParseException e) { logger.error(e); return response; } } } final Date lastSupportedDate = DateUtil.convertToDate( response.header(HEADER_APP_VERSION_LAST_SUPPORTED_DATE)); final boolean isUnsupported = response.code() == HttpStatus.UPGRADE_REQUIRED; NewVersionAvailableEvent.post(appLatestVersion, lastSupportedDate, isUnsupported); return response; }

Target:
public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); final Version appLatestVersion; { final String appLatestVersionString = response.header(HEADER_APP_LATEST_VERSION); if (appLatestVersionString == null) { appLatestVersion = null; } else { try { appLatestVersion = new Version(appLatestVersionString); } catch (ParseException e) { logger.error(e, true); return response; } } } final Date lastSupportedDate = DateUtil.convertToDate( response.header(HEADER_APP_VERSION_LAST_SUPPORTED_DATE)); final boolean isUnsupported = response.code() == HttpStatus.UPGRADE_REQUIRED; NewVersionAvailableEvent.post(appLatestVersion, lastSupportedDate, isUnsupported); return response; }
Source:
private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: ListObjectsV2Result result = s3.listObjectsV2(host, keyFromPath(path)); boolean isGlacierObject = result.getObjectSummaries().stream() .anyMatch(summary -> summary.getStorageClass().equals(StorageClass.Glacier.toString())); if (isGlacierObject) { return new ByteArrayInputStream(new byte[0]); } case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw e; } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throwIfInstanceOf(e, IOException.class); throwIfUnchecked(e); throw new RuntimeException(e); } }

Target:
private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw e; } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throwIfInstanceOf(e, IOException.class); throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
public static Class<?> getStackClass1() { return getStackClass2(); }

Target:
public static Class<?> getStackClass1() throws ClassNotFoundException { return getStackClass2(); }
Source:
private String setParameter(HttpMessage msg, NameValuePair originalPair, String value) { String contentType = msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE); String boundary = getBoundary(contentType); StringBuilder newBodyBuilder = new StringBuilder(msg.getRequestBody().toString()); int idx = originalPair.getPosition() -1; MultipartFormParameter mpPart = multiPartParams.get(idx); if (LOGGER.isDebugEnabled()) { LOGGER.debug("i: " + idx + " pos: " + originalPair.getPosition() + " S: " + mpPart.getStart() + " E: " + mpPart.getEnd()); } if (idx == originalPair.getPosition()-1) { newBodyBuilder.replace(mpPart.getStart(), mpPart.getEnd(), value); } String newBody = newBodyBuilder.toString(); msg.getRequestBody().setBody(newBody); return newBody; }

Target:
private String setParameter(HttpMessage msg, NameValuePair originalPair, String value) { StringBuilder newBodyBuilder = new StringBuilder(msg.getRequestBody().toString()); int idx = originalPair.getPosition() -1; MultipartFormParameter mpPart = multiPartParams.get(idx); if (LOGGER.isDebugEnabled()) { LOGGER.debug("i: " + idx + " pos: " + originalPair.getPosition() + " S: " + mpPart.getStart() + " E: " + mpPart.getEnd()); } newBodyBuilder.replace(mpPart.getStart(), mpPart.getEnd(), value); String newBody = newBodyBuilder.toString(); msg.getRequestBody().setBody(newBody); return newBody; }